package com.crm.customers.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.crm.base.controller.BaseController;
import com.crm.customers.model.Article;
import com.crm.customers.model.Commission;
import com.crm.customers.model.CommissionCustomer;
import com.crm.customers.model.ContactsDynamicInfo;
import com.crm.customers.model.Contract;
import com.crm.customers.model.ContractMoneylog;
import com.crm.customers.model.CusService;
import com.crm.customers.model.CustomerCategory;
import com.crm.customers.model.CustomerClaim;
import com.crm.customers.model.CustomerContacts;
import com.crm.customers.model.CustomerFiles;
import com.crm.customers.model.CustomerInfo;
import com.crm.customers.model.CustomerInfoTemp;
import com.crm.customers.model.CustomerQualificationItem;
import com.crm.customers.model.CustomerQualificationUser;
import com.crm.customers.model.CustomerRecyclebin;
import com.crm.customers.model.Paid;
import com.crm.customers.service.ArticleService;
import com.crm.customers.service.CommissionCustomerService;
import com.crm.customers.service.CommissionService;
import com.crm.customers.service.ContactsDynamicInfoService;
import com.crm.customers.service.ContractMoneylogService;
import com.crm.customers.service.ContractService;
import com.crm.customers.service.CusSerService;
import com.crm.customers.service.CustomerCategoryService;
import com.crm.customers.service.CustomerClaimService;
import com.crm.customers.service.CustomerContactsService;
import com.crm.customers.service.CustomerFilesService;
import com.crm.customers.service.CustomerInfoTempService;
import com.crm.customers.service.CustomerRecyclebinService;
import com.crm.customers.service.CustomerService;
import com.crm.customers.service.PaidService;
import com.crm.sys.model.Configure;
import com.crm.sys.model.ConfigureItem;
import com.crm.sys.model.FilesInfo;
import com.crm.sys.model.Log;
import com.crm.sys.model.Province;
import com.crm.sys.service.FilesInfoService;
import com.crm.sys.service.SysService;
import com.crm.user.model.UserAccount;
import com.crm.user.model.UserInfo;
import com.crm.user.service.UserService;
import com.crm.util.CommonUtil;
import com.crm.util.Constants;
import com.crm.util.CrmUtil;
import com.crm.util.Pager;
import com.crm.util.XLSUtil;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;

/**
 * 客户管理Controller
 * */
@Controller
public class CustomerController extends BaseController {
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private ContactsDynamicInfoService contactsDynamicInfoService;
	
	@Autowired
	private CustomerContactsService customerContactsService;
	
	@Autowired
	private SysService sysService;
	
	@Autowired
	private FilesInfoService filesInfoService;
	
	@Autowired
	private CustomerFilesService customerFilesService;
	
	@Autowired
	private CustomerCategoryService CustomerCategoryService;
	
	@Autowired
	private UserService userService;
	@Autowired
	private ContractMoneylogService contractMoneylogService;
	@Autowired
	private ContractService contractService;
	@Autowired
	private CustomerClaimService customerClaimService;
	@Autowired
	private CustomerRecyclebinService customerRecyclebinService;
	@Autowired
	private CommissionService commissionService;
	@Autowired
	private CommissionCustomerService commissionCustomerService;
	@Autowired
	private ArticleService articleService;
	@Autowired
	private CustomerInfoTempService customerInfoTempService;
	@Autowired
	private CusSerService cusSerService;
	@Autowired
	private PaidService paidService;
	
	
	/**
	 *  删除资源人员 
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/updqualificationuser", method = RequestMethod.POST)
	@ResponseBody
	public String upddelcustomerQualificationInfoUser(@ModelAttribute CustomerQualificationUser c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long id = getLoginUser().getId();
		c.setUpdateuser(id);  
		int result = customerService.updateQualificationUser(c);
		return JSON.toJSONString(result);
	}
	
	/**
	 *  删除资源人员 
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/delqualificationuser", method = RequestMethod.POST)
	@ResponseBody
	public String delcustomerQualificationInfoUser(@ModelAttribute CustomerQualificationUser c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long id = getLoginUser().getId();
		c.setUpdateuser(id);  
		c.setIsdel(1);
		int result = customerService.deleteQualificationUser(c);
		return JSON.toJSONString(result);
	}
	
	/**
	 *  资质人员新增
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/savecusstomerqualificationuser", method = RequestMethod.POST)
	@ResponseBody
	public String savecustomerQualificationUser(@ModelAttribute CustomerQualificationUser c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long id = getLoginUser().getId();
		c.setType(1);
		c.setCreateuser(id);
		c.setUpdateuser(id); 
		int result = customerService.insertQualificationUser(c);
		return JSON.toJSONString(result);
	}
	/**
	 *  资质从业人员列表
	 * @throws UnsupportedEncodingException 
	 * */ 
	@RequestMapping(value="/customer/qualificationuserlist")
	public String customerQualificationUserList(@ModelAttribute CustomerInfo c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		//获取部门下所有人
	    List<UserInfo> userlist = userService.getUserInfoListWithDept();
		
		List<CustomerInfo> conlist = customerService.getCustomerQualificationUserList(c, getSkipToPage(), pageSize);
		Pager pager = new Pager( getSkipToPage(), pageSize);
		pager.setResultList(conlist);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",c.getKeyWord());
		params.put("currentcusid",c.getId());
		params.put("contractid",c.getContractid());
		params.put("source",c.getSource());
		params.put("owner",request.getParameter("owner"));
		pager.setParams(params);
		request.setAttribute("uid", getLoginUser().getId());
		request.setAttribute("pager", pager);
		request.setAttribute("userlist", userlist);
		return "/customermanage/qualificationuserlist";
	}
	
	/**
	 *  资质从业人员列表
	 * @throws UnsupportedEncodingException 
	 * */ 
	@RequestMapping(value="/customer/qualificationuserhistorylist")
	public String customerQualificationHistoryUserList(@ModelAttribute CustomerInfo c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		//获取部门下所有人
	    //List<UserInfo> userlist = userService.getUserInfoListWithDept();
		
		List<CustomerInfo> conlist = customerService.getQualificationCustomerList(c, getSkipToPage(), pageSize);
		Pager pager = new Pager( getSkipToPage(), pageSize);
		pager.setResultList(conlist);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",c.getKeyWord());  
		params.put("source",c.getSource());
		params.put("quid",c.getQuid());
		pager.setParams(params);
		request.setAttribute("uid", getLoginUser().getId());
		request.setAttribute("pager", pager);
		//request.setAttribute("userlist", userlist);
		return "/customermanage/qualificationuserhistorylist";
	}
	
	
	/**
	 *  资质跟进记录列表
	 * @throws UnsupportedEncodingException 
	 * */ 
	@RequestMapping(value="/customer/qualificationitemlist")
	public String customerQualificationItemList(@ModelAttribute CustomerQualificationItem c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		pageSize =100;
		//资质要求
		Configure   cf = sysService.getConfigureByName("customer_zzyq");
		List<ConfigureItem>   item  = cf.getItem();
		//资质项列表
		Configure   cfTwo = sysService.getConfigureByName("customer_zzitem");
		List<ConfigureItem>   itemTwo  = cfTwo.getItem();
		
		
		
		List<CustomerQualificationItem> conlist = customerService.getCustomerQualificationItemList(c, getSkipToPage(), pageSize);
		Pager pager = new Pager( getSkipToPage(), pageSize);
		pager.setResultList(conlist);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",c.getKeyWord());
		params.put("currentcusid",c.getCusid());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("yq",item);
		request.setAttribute("item",itemTwo);
		return "/customermanage/qualificationitemlist";
	}
	/**
	 * 查询资源跟进记录详情
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/qualificationiteminfo", produces="text/html;charset=UTF-8",method = RequestMethod.POST)
	@ResponseBody
	public String customerQualificationInfoItemInfo(@ModelAttribute CustomerQualificationItem c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		CustomerQualificationItem   citem = customerService.getByParamsQualificationItem(c);
		return JSON.toJSONString(citem);
	}
	
	
	/**
	 * 修改资源跟进记录
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/savequalificationitem", method = RequestMethod.POST)
  public String updateCustomerQualificationInfoItem(Long cusid,Long contractid,Integer[] itemid, String[] content, HttpServletResponse response,HttpServletRequest request,
				RedirectAttributes redirectAttributes) throws Exception{	
	    Long uid = getLoginUser().getId();
		int result =  customerService.saveQualificationItem(uid,cusid, contractid, itemid, content);
		return "redirect:/customer/qualificationitemlist?cusid="+cusid+"&contractid="+contractid+"&owner="+request.getParameter("owner");
	}
	
	
	/**
	 * 修改资源跟进记录
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/updatequalificationitem", method = RequestMethod.POST)
	@ResponseBody
	public String updateCustomerQualificationInfoItem(@ModelAttribute CustomerQualificationItem c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{ 
		Long id = getLoginUser().getId();
		c.setUpdateuser(id); 
		int result = customerService.updateQualificationItem(c);
		return JSON.toJSONString(result);
	}
	
	/**
	 *  删除资源跟进记录
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/delqualificationitem", method = RequestMethod.POST)
	@ResponseBody
	public String delcustomerQualificationInfoItem(@ModelAttribute CustomerQualificationItem c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long id = getLoginUser().getId();
		c.setUpdateuser(id); 
		c.setIsdel(1);
		int result = customerService.updateQualificationItem(c);
		return JSON.toJSONString(result);
	}
	/**
	 *  资质管理用户分配
	 * @throws UnsupportedEncodingException 
	 * */
/*	@RequestMapping(value="/customer/savequalificationitem", method = RequestMethod.POST)
	@ResponseBody
	public String savecustomerQualificationInfoItem(@ModelAttribute CustomerQualificationItem c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long id = getLoginUser().getId();
		c.setCreateuser(id);
		c.setUpdateuser(id); 
		int result = customerService.insertQualificationItem(c);
		return JSON.toJSONString(result);
	}*/
	
	
	/**
	 *  资质管理用户分配
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/savequalificationuser", method = RequestMethod.POST)
	@ResponseBody
	public String savecustomerQualificationInfouser(@ModelAttribute CustomerQualificationUser c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long id = getLoginUser().getId();
		c.setType(0);
		c.setCreateuser(id);
		c.setUpdateuser(id); 
		int result = customerService.insertQualificationUser(c);
		return JSON.toJSONString(result);
	}
	
	
	/**
	 *  资质客户分配列表
	 * @throws UnsupportedEncodingException 
	 * */ 
	@RequestMapping(value="/customer/myqualificationlist")
	public String customermyQualificationInfoList(@ModelAttribute CustomerInfo c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long id = getLoginUser().getId();
	   c.setUid(id);
		List<CustomerInfo> conlist = customerService.getCustomerQualificationInfoList(c, getSkipToPage(), pageSize);
		Pager pager = new Pager( getSkipToPage(), pageSize);
		pager.setResultList(conlist);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",c.getKeyWord());
	 	params.put("uid",c.getUid());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		return "/customermanage/myqualificationlist";
	}
	
	/**
	 *  资质客户分配列表
	 * @throws UnsupportedEncodingException 
	 * */ 
	@RequestMapping(value="/customer/qualificationlist")
	public String customerQualificationInfoList(@ModelAttribute CustomerInfo c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long deptid = getLoginUser().getInfo().getDeptid();
		//获取部门下所有人
	    List<UserInfo> userlist = userService.getAllUserListByDeptId(deptid);
		
		List<CustomerInfo> conlist = customerService.getCustomerQualificationInfoList(c, getSkipToPage(), pageSize);
		Pager pager = new Pager( getSkipToPage(), pageSize);
		pager.setResultList(conlist);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",c.getKeyWord());
	 	params.put("uid",c.getUid());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("userlist", userlist);
		return "/customermanage/qualificationlist";
	}
	
	
	
	/**
	 * 代办管理url拼接
	 * */
	@RequestMapping(value="/customer/commurl")
	public String intoCommUrlList(String keyWord,String state, String consign,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "/customer/commlist";
		url += "p"+getSkipToPage();
		if (state != null && state.length() > 0) {
			url += "_s"+ state;
		}
		if (consign != null && consign.length() > 0) {
			url += "_c"+ consign;
		}
		if (!Strings.isNullOrEmpty(keyWord)){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(keyWord, "UTF-8"),"UTF-8");
		}
		return "redirect:"+url;
	}
	
	/**
	 * 进入代办管理
	 * */
	@RequestMapping(value="/customer/commlist{k}")
	public String intoCommList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		Integer pageNo = getSkipToPage();
		Integer pageSize = 10;
		String keyWord = null;
		Integer state = null;
		Integer consign = null;
		
		String key[] = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p",""));
			} else if (kk.indexOf("s") > -1) {
				state = Integer.parseInt(kk.replace("s", ""));
			} else if (kk.indexOf("c") > -1) {
				consign = Integer.parseInt(kk.replace("c", ""));
			}
		}
		if(request.getParameter("kwd")!=null){
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		//获取代办建造师列表
		CommissionCustomer cc = new CommissionCustomer();
		cc.setKeyWord(keyWord);
		if(state != null){
			cc.setState(state);
		}
		if (consign != null) {
			cc.setConsign(consign);
		}
		List<CommissionCustomer> list = commissionCustomerService.getAllComCusListByParams(cc, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("state", state);
		params.put("consign", consign);
		params.put("keyWord", keyWord);
		pager.setParams(params);
		request.setAttribute("pager", pager);
		return "financemanage/commlist";
	}
	
	
	
	/**
	 * 保存放入回收站的资源
	 * @throws Exception 
	 * */
	@RequestMapping(value="/customer/recyclebinsave", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String saveRecyclebin(@ModelAttribute CustomerRecyclebin c,String value,   HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 int  i = 0;
		
		if (!Strings.isNullOrEmpty(value)){
			
			Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(value);
	        for (String idStr : splitStr) {
	        	CustomerRecyclebin  cr = new CustomerRecyclebin();
	        	cr.setUpdateuser(getLoginUser().getId());
	        	cr.setCusid(Long.parseLong(idStr));
	        	i = customerRecyclebinService.saveCustomerRecyclebin(cr);
	        }
			 
		}else {
			 c.setUpdateuser(getLoginUser().getId());
			i = customerRecyclebinService.saveCustomerRecyclebin(c);
		}
		
		
		 return JSONArray.toJSONString(i);
	}
	 
	

	/**
	 * 资源回收站URL拼接
	 * @throws Exception 
	 * */
	@RequestMapping(value="/customer/recyclebinlisturl",produces="text/html;charset=UTF-8")
	public String Recyclebinlistturl(@ModelAttribute CustomerRecyclebin c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/customer/recyclebinlist";
		url += "p"+getSkipToPage();
		if (c.getState() != null) {
			url += "_s"+c.getState();
		}
		if (!Strings.isNullOrEmpty(c.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(c.getKeyWord(), "UTF-8"),"UTF-8");
		}
		return "redirect:" + url;
	}
	 
	
	/**
	 *  资源回收站列表页面
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/recyclebinlist{k}", produces="text/html;charset=UTF-8")
	public String recyclebinList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
	 
		Integer pageNo = 1;
		Integer pageSize = 10;
		String keyWord = null;
		
		CustomerRecyclebin cc = new CustomerRecyclebin();
		//c.setType(1);
		cc.setState(0);//标识 待审批
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				} else if (kk.indexOf("s") > -1) {
					cc.setState(Integer.parseInt(kk.replace("s", "")));
				}
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			cc.setKeyWord(keyWord);
		}
		
		List<CustomerRecyclebin> conlist = customerRecyclebinService.getCustomerRecyclebinList(cc, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(conlist);
		pager.setUrl("/customer/recyclebinlist"+k);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",keyWord);
		params.put("state",cc.getState());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		return "/customermanage/recyclebinlist";
	}
	
	

	/**
	 * 需求列表url拼接
	 * p{page}_c{category}_t{types}_r{paperspurpose}_s{stime}_e{etime}?kwd=
	 * */
	@RequestMapping(value="/customer/categoryneedurl")
	public String intoCategoryNeedUrl(@ModelAttribute CustomerCategory cc,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		String url = "/customer/categoryneedlist";
		url += "p"+getSkipToPage();
		if (cc.getBuystate()!= null) {
			url += "_gq"+cc.getBuystate();
		}
		if (cc.getType()!= null) {
			url += "_lx"+cc.getType();
		}
		if (cc.getCategory() != null) {
			url += "_c"+cc.getCategory();
		}
		if (cc.getTypes() != null) {
			url += "_t"+cc.getTypes();
		}
		if (cc.getPaperspurpose() != null) {
			url += "_r"+cc.getPaperspurpose();
		}
		if (cc.getStime() != null && cc.getStime().length()>0) {
			url += "_s" +cc.getStime();
		}
		if (cc.getEtime() != null && cc.getEtime().length()>0) {
			url += "_e" + cc.getEtime();
		}
		if (!Strings.isNullOrEmpty(cc.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(cc.getKeyWord(), "UTF-8"),"UTF-8");
		}
		return "redirect:"+url;
	}
	
	
	/**
	 * 进入需求列表
	 * p{page}_c{category}_t{types}_r{paperspurpose}_s{stime}_e{etime}?kwd=
	 * */
	@RequestMapping(value="/customer/categoryneedlist{k}")
	public String intoCategoryNeedList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		Integer pageNo = getSkipToPage();
		Integer pageSize = 10;
		CustomerCategory cc = new CustomerCategory();
		String[] key = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("gq") > -1) {
				cc.setBuystate( Integer.parseInt(kk.replace("gq", "")));
			} else 	if (kk.indexOf("lx") > -1) {
				cc.setType( Integer.parseInt(kk.replace("lx", "")));
			} else if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p", ""));
			} else if (kk.indexOf("c") > -1) {
				cc.setCategory(Integer.parseInt(kk.replace("c", "")));
			} else if (kk.indexOf("t") > -1) {
				cc.setTypes(Integer.parseInt(kk.replace("t", "")));
			} else if (kk.indexOf("r") > -1) {
				cc.setPaperspurpose(Integer.parseInt(kk.replace("r", "")));
			} else if (kk.indexOf("s") > -1) {
				cc.setStime(kk.replace("s", ""));
			} else if (kk.indexOf("e") > -1) {
				cc.setEtime(kk.replace("e", ""));
			}
		}
		if(request.getParameter("kwd")!=null){
			cc.setKeyWord(URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		//要展示的数据很多啊...
		//企业名称,所需证书,所需数量,证书类型,证书用途,结束时间,发起人
		List<CustomerCategory> list = CustomerCategoryService.getCustomerCategoryListByParams(cc, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		//传参
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("category", cc.getCategory());
		map.put("types", cc.getTypes());
		map.put("type", cc.getType());
		map.put("buystate", cc.getBuystate());
		map.put("paperspurpose", cc.getPaperspurpose());
		map.put("stime", cc.getStime());
		map.put("etime", cc.getEtime());
		map.put("keyWord", cc.getKeyWord());
		pager.setParams(map);
		request.setAttribute("pager", pager);
		return "/customermanage/categorylist";
	}
	
	
	/**
	 * 保存索要资源
	 * @throws Exception 
	 * */
	@RequestMapping(value="/customer/claimsave", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String saveclaim(@ModelAttribute CustomerClaim c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 c.setUpdateuser(getLoginUser().getId());
		 int  i = customerClaimService.saveCustomerClaim(c);
		 return JSONArray.toJSONString(i);
	}
	 
	

	/**
	 * 索要资源URL拼接
	 * @throws Exception 
	 * */
	@RequestMapping(value="/customer/claimlisturl",produces="text/html;charset=UTF-8")
	public String claimlistturl(@ModelAttribute CustomerClaim c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/customer/claimlist";
		url += "p"+getSkipToPage();
		if (c.getState() != null) {
			url += "_s"+c.getState();
		}
		if (!Strings.isNullOrEmpty(c.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(c.getKeyWord(), "UTF-8"),"UTF-8");
		}
		return "redirect:" + url;
	}
	 
	
	/**
	 *  索要资源列表页面
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/claimlist{k}", produces="text/html;charset=UTF-8")
	public String claimList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
	 
		Integer pageNo = 1;
		Integer pageSize = 10;
		String keyWord = null;
		
		CustomerClaim cc = new CustomerClaim();
		//c.setType(1);
		cc.setState(0);//标识 待审批
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				} else if (kk.indexOf("s") > -1) {
					cc.setState(Integer.parseInt(kk.replace("s", "")));
				}
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			cc.setKeyWord(keyWord);
		}
		
		List<CustomerClaim> conlist = customerClaimService.getCustomerClaimList(cc, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(conlist);
		pager.setUrl("/customer/claimlist"+k);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",keyWord);
		params.put("state",cc.getState());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		return "/customermanage/claimlist";
	}
	
	
	/**
	 * 客户文件信息列表
	 * */
	@RequestMapping(value="/customer/filesinfo{k}", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getCustomerinfoFiles(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//先要获取信息表的id
		Long id = Long.parseLong(k);
		//然后就是根据信息表id获取信息详情了（里面包含了联系人表）
		CustomerInfo ci = customerService.getCustomerInfoById(id);
		if(ci!=null&&ci.getFilesItem()!=null){
			return JSONArray.toJSONString(ci.getFilesItem());
		}
		return null;
	}
	
	/**
	 * 业绩统计URL拼接
	 * @throws Exception 
	 * */
	@RequestMapping(value="/achievement/listurl",produces="text/html;charset=UTF-8")
	public String achievementlistturl(@ModelAttribute Contract c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/achievement/list";
		url += "p"+getSkipToPage();
		if (c.getSttime() != null) {
			url += "_st"+c.getSttime();
		}
		if (c.getEntime() != null) {
			url += "_et" + c.getEntime();
		}
		if (c.getType() != null) {
			url += "_ty" + c.getType();
		}
		if (!Strings.isNullOrEmpty(c.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(c.getKeyWord(), "UTF-8"),"UTF-8");
		}
		return "redirect:" + url;
	}
	 
	
	/**
	 * 业绩统计列表页面
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/achievement/list{k}", produces="text/html;charset=UTF-8")
	public String achievementlistList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "customermanage/achievementlist";
		Integer pageNo = 1;
		Integer pageSize = 10;
		String keyWord = null;
		
		Contract c = new Contract();
		c.setState(99);//标识 为已完成回款的
		c.setUid(getLoginUser().getId());
		
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				} else if (kk.indexOf("st") > -1) {
					c.setSttime(kk.replace("st", ""));
				} else if (kk.indexOf("et") > -1) {
					c.setEntime(kk.replace("et", ""));
				} else if (kk.indexOf("ty") >-1) {
					if (Integer.parseInt(kk.replace("ty", "")) > -1){
						c.setType(Integer.parseInt(kk.replace("ty", "")));
					} else {
						c.setType(null);
					}
					
				}
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			c.setKeyWord(keyWord);
		}
		
		//获取业绩统计列表
		List<Contract> conlist = contractService.getContractByPerformanceList(c, pageNo, pageSize);
		
		Integer totalmoney = 0;
		totalmoney = contractService.getAllApprovemoney(c);
		
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(conlist);
		pager.setUrl("/achievement/list"+k);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",keyWord);
		//params.put("Signingtime", c.getSigningtime());
		params.put("sttime",c.getSttime());
		params.put("entime", c.getEntime());
		params.put("type", c.getType());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("totalmoney", totalmoney);
		return url;	
	}
	
	
	/**
	 * 业绩管理URL拼接
	 * @throws Exception 
	 * */
	@RequestMapping(value="/achievement/manageurl",produces="text/html;charset=UTF-8")
	public String achievementmanageurl(@ModelAttribute Contract c,@ModelAttribute UserInfo ui,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/achievement/manage";
		url += "p"+getSkipToPage();
		if (c.getSttime() != null) {
			url += "_st"+c.getSttime();
		}
		if (c.getEntime() != null) {
			url += "_et" + c.getEntime();
		}
		if (ui.getDeptid() != null) {
			url += "_d" + ui.getDeptid();
		}
		if (ui.getUid() != null) {
			url += "_u" + ui.getUid();
		}
		if (!Strings.isNullOrEmpty(c.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(c.getKeyWord(), "UTF-8"),"UTF-8");
		}
		return "redirect:" + url;
	}
	

	/**
	 * 业绩管理导出excel
	 * @throws Exception 
	 * */
	@RequestMapping(value="/achievement/export", method = RequestMethod.POST)
	public void exportachievement(@ModelAttribute Contract c,@ModelAttribute UserInfo ui,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		try{
			c.setState(99);//标识 为已完成回款的
			c.setType(0);
			//根据deptid获取下面所有的子id
			List<Long> dpsonlist = sysService.getAllDeptmentidByPid(c.getDeptid());
			c.setSondpidlist(dpsonlist);
			List<Contract>  rc = contractService.getContractByPerformanceList(c);
			c.setType(1);
			List<Contract>  qy = contractService.getContractByPerformanceList(c);
			
			 byte[] fileNameByte = ("yeji.xls").getBytes("GBK");  
	         String filename = new String(fileNameByte, "ISO8859-1");  

	         byte[] bytes = XLSUtil.downAchievement(rc, qy);
	         response.setContentType("application/x-msdownload");  
	         //response.setContentType("application/x-excel");    
	         response.setContentLength(bytes.length);  
	         response.setHeader("Content-Disposition", "attachment;filename="  
	                 + filename);  
	         response.getOutputStream().write(bytes);  
		}catch(Exception e){
			
		}
		
         //response.getOutputStream().flush();  
	}
	
	
	
	/**
	 * 业绩管理页面
	 * 如果部门id为0,那就是查所有的总业绩
	 * 如果部门id不为0,uid为0,那就是查该部门的总业绩
	 * 如果部门id和uid都不为0,那就查这个人的总业绩
	 * */
	@RequestMapping(value="/achievement/manage{k}",produces="text/html;charset=UTF-8")
	public String achievementManage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
 		String url = "customermanage/achievementmanage";
		Integer pageNo = 1;
		Integer pageSize = 10;
		String keyWord = null; 
		Long uid = 0L; //uid
		Long deptid = getLoginUser().getInfo().getDeptid(); //部门id
		Integer totalmoney = 0; //总业绩
		
		Contract c = new Contract();
		c.setState(99);//标识 为已完成回款的
				
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				} else if (kk.indexOf("st") > -1) {
					c.setSttime(kk.replace("st", ""));
				} else if (kk.indexOf("et") > -1) {
					c.setEntime(kk.replace("et", ""));
				} else if (kk.indexOf("d") > -1) {
					//部门id
					deptid = Long.parseLong(kk.replace("d", ""));
				} else if (kk.indexOf("u") > -1) {
					//uid
					uid = (Long.parseLong(kk.replace("u", "")));
				} 
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			c.setKeyWord(keyWord);
		}
		
		c.setUid(uid);
		c.setDeptid(deptid);
		
		//根据deptid获取下面所有的子id
		List<Long> dpsonlist = sysService.getAllDeptmentidByPid(deptid);
		c.setSondpidlist(dpsonlist);
		
		//获取业绩统计列表
		List<Contract> conlist = contractService.getContractByPerformanceList(c, pageNo, pageSize);
		totalmoney = contractService.getAllApprovemoney(c);
		
		
		//获取登录人的部门id
		UserAccount user = userService.getUserAccountInfoById(getLoginUser().getId());
		Long udid = user.getDept().getId();
		 
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(conlist);
		pager.setUrl("/achievement/list"+k);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",keyWord);
		params.put("sttime",c.getSttime());
		params.put("entime", c.getEntime());
		params.put("uid", uid);
		params.put("deptid", deptid);
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("totalmoney", totalmoney);
		request.setAttribute("udid", udid);
		return url;
	}
	
	/**
	 * 签单到账URL拼接
	 * @throws Exception 
	 * */
	@RequestMapping(value="/myarrival/arrivallisturl",produces="text/html;charset=UTF-8")
	public String arrivallistturl(@ModelAttribute Contract c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/myarrival/arrivallist";
		url += "p"+getSkipToPage();
		
		if (c.getSttime() != null) {
			url += "_st"+c.getSttime();
		}
		if (c.getEntime() != null) {
			url += "_et" + c.getEntime();
		}
		if (!Strings.isNullOrEmpty(c.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(c.getKeyWord(), "UTF-8"),"UTF-8");
		}
		return "redirect:" + url;
	}
	 
	
	/**
	 * 签单到账列表页面
	 * 主要就是企业的,一条一条的记录,跟人才没有关系
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/myarrival/arrivallist{k}", produces="text/html;charset=UTF-8")
	public String arrivallistList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "customermanage/arrivallist";
		Integer pageNo = 1;
		Integer pageSize = 10;
		String keyWord = null;
		
		ContractMoneylog c = new ContractMoneylog();
		c.setType(1);
		c.setApprovalstatus(Constants.ApproveState.TOW);
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				} else if (kk.indexOf("st") > -1) {
					c.setSttime(kk.replace("st", ""));
				} else if (kk.indexOf("et") > -1) {
					c.setEntime(kk.replace("et", ""));
				}
			}
		}
		
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			c.setKeyWord(keyWord);
		}
		
		//必要的条件:必须是企业,必须是审核通过的然后createuser是自己
		c.setCreateuser(getLoginUser().getId());
		List<ContractMoneylog> list = contractMoneylogService.getContractMoneylogList(c, pageNo, pageSize);
		int totalmoney = contractMoneylogService.selectTotalMoney(c);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		pager.setUrl("/myarrival/arrivallist"+k);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",keyWord);
		params.put("sttime",c.getSttime());
		params.put("entime", c.getEntime());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("totalmoney", totalmoney);
		return url;	
	}
	
	
	
	

	/**
	 * 垫款URL拼接
	 * @throws Exception 
	 * */
	@RequestMapping(value="/makeadvances/paymentlisturl",produces="text/html;charset=UTF-8")
	public String paymentlisturl(@ModelAttribute ContractMoneylog c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/makeadvances/paymentlist";
		url += "p"+getSkipToPage();
		if (c.getState() != null && c.getState() != -1) {
			url += "_s"+c.getState();
		}
		if (c.getApprovalstatus() != null && c.getApprovalstatus() != -1) {
			url += "_a"+c.getApprovalstatus();
		}
		if (!Strings.isNullOrEmpty(c.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(c.getKeyWord(), "UTF-8"),"UTF-8");
		}
		return "redirect:" + url;
	}

	/**
	 * 进入垫款列表页面
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/makeadvances/paymentlist{k}", produces="text/html;charset=UTF-8")
	public String intoReceivablesList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "customermanage/paymentlist";
		Integer pageNo = 1;
		Integer pageSize = 10;
		String keyWord = null;
		
		ContractMoneylog c = new ContractMoneylog();
		c.setType(0);
		c.setPaytype(0);//预付款
		c.setCreateuser(getLoginUser().getId());
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				}  
				if (kk.indexOf("a") > -1) {
					c.setApprovalstatus(Integer.parseInt(kk.replace("a", "")));
				}
				if (kk.indexOf("s") > -1) {
					c.setState(Integer.parseInt(kk.replace("s", "")));
				}
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			c.setKeyWord(keyWord);
		}
		List<ContractMoneylog>  list = contractMoneylogService.getContractMoneylogList(c, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		pager.setUrl("/makeadvances/paymentlist"+k);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",keyWord);
		params.put("state", c.getState());
		params.put("approvalstatus", c.getApprovalstatus());
		params.put("type", c.getType());
		params.put("arrivaltime", c.getArrivaltime());
		pager.setParams(params);
		request.setAttribute("pager", pager); 
		return url;	
	}
	
	
	/**
	 * 便捷链接展示页面
	 * */
	@RequestMapping(value="/linkpage")
	public String linkPageInfo(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//获取当前用户的uid
		Long uid = getLoginUser().getId();
		//创建一个文章表对象,查询文章表含有的省份名称
		Article art = new Article();
		art.setCreateuser(uid);
		List<Province> prolist = articleService.getUserProvinceNameList(art);
		art.setIsdel(0);
		List<Article> list = articleService.getArticleListByParams(art);
		request.setAttribute("list", list);
		request.setAttribute("prolist", prolist);
		return "/customermanage/link1";
	}
	
	/**
	 * ajax获取需要展示的内容
	 * */
	@RequestMapping(value="/linkpagehtml", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getLinksByParams(String type,String proid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		Article art = new Article();
		art.setCreateuser(getLoginUser().getId());
		art.setIsdel(0);
		if (type != null && type.length() > 0 && Integer.parseInt(type) > -1) {
			art.setType(Integer.parseInt(type));
		}
		if (proid != null && proid.length() > 0 && Long.parseLong(proid) > 0) {
			art.setProvinceid(Long.parseLong(proid));
		}
		List<Article> list = articleService.getArticleListByParams(art);
		return JSON.toJSONString(list);
	}
	
	
	/**
	 * 便捷链接url拼接
	 * 
	 * */
	@RequestMapping(value="/linkurl")
	public String linkUrl(@ModelAttribute Article art,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "/links";
		url += "p"+getSkipToPage();
		if (art.getProvinceid() != null) {
			url += "_r"+art.getProvinceid();
		}
		if (art.getType() != null) {
			url += "_t"+art.getType();
		}
		if (!Strings.isNullOrEmpty(art.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(art.getKeyWord(), "UTF-8"),"UTF-8");
		}
		
		return "redirect:" + url;
	}
	
	
	/**
	 * 便捷链接 
	 */
	@RequestMapping(value = "/links{k}")
	public String linkInfo(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		Integer pageNo = getSkipToPage();
		Integer pageSize = 10;
		Long proid = null;
		Integer type = null;
		String keyWord = null;
		
		Article art = new Article();
		
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				} else if (kk.indexOf("r") > -1) {
					proid = Long.parseLong(kk.replace("r", ""));
				} else if (kk.indexOf("t") > -1) {
					type = Integer.parseInt(kk.replace("t", ""));
				}
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			art.setKeyWord(keyWord);
		}
		if (proid != null) {
			art.setProvinceid(proid);
		}
		if (type != null) {
			art.setType(type);
		}
		art.setIsdel(0);
		art.setCreateuser(getLoginUser().getId());
		//获取列表
		List<Article> list = articleService.getArticleListByParams(art,pageNo,pageSize);
		//pager
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("keyWord",keyWord);
		params.put("type",type);
		params.put("proid",proid);
		pager.setParams(params);
		request.setAttribute("pager", pager);
		
		return "/customermanage/link" ;
	}
	
	/**
	 * 便捷链接省份获取
	 * */
	@RequestMapping(value="/linkprovince", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getLinkProvince(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		//获取当前用户的uid
		Long uid = getLoginUser().getId();
		//创建一个文章表对象,查询文章表含有的省份名称
		Article art = new Article();
		art.setCreateuser(uid);
		List<Province> list = articleService.getUserProvinceNameList(art);
		return JSON.toJSONString(list);
	}
	
	/**
	 * 删除便捷链接
	 * */
	@RequestMapping(value="/deletelink")
	@ResponseBody
	public String deleteArticle(long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		Article a = new Article();
		a.setId(id);
		a.setIsdel(1);
		a.setCreateuser(getLoginUser().getCreateuser());
		articleService.deleteArticle(a);
		return JSON.toJSONString(1);
	}
	
	/**
	 * 批量删除便捷链接
	 * */
	@RequestMapping(value="/pldeletelink")
	@ResponseBody
	public String pldeleteArticle(String ids,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		String idss[] = ids.split(",");
		Article a = new Article();
		a.setIsdel(1);
		a.setCreateuser(getLoginUser().getCreateuser());
		for (String id : idss) {
			a.setId(Long.parseLong(id));
			articleService.deleteArticle(a);
		}
		return JSON.toJSONString(1);
	}
	
	/**
	 * 保存文件
	 * */
	@RequestMapping(value="/savelinkfile")
	public String saveLinkFile(@RequestParam MultipartFile[] file,String filetitle,String fileproid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//上传文件
		List<MultipartFile> files = Arrays.asList(file);
		List<FilesInfo> list = filesInfoService.saveFile(files);
		//文章表基础
		Article art = new Article();
		art.setCreateuser(getLoginUser().getId());
		art.setTitle(filetitle);
		art.setType(2);
		art.setProvinceid(Long.parseLong(fileproid));
		art.setIsdel(0);
		//循环获取内容(存入fileid)
		for (FilesInfo f : list) {
			art.setContent(f.getId().toString());
			//保存
			articleService.savearticle(art);
		}
		return "redirect:/linkurl";
	}
	
	/**
	 * 保存链接
	 * */
	@RequestMapping(value="/savelinkurl")
	public String saveLinkUrl(String urltitle,String url,String urlartid,String urlproid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		//文章表基础
		Article art = new Article();
		if (urlartid != null && urlartid.length() > 0 && Integer.parseInt(urlartid) > 0) {
			art.setId(Long.parseLong(urlartid));
		}
		art.setCreateuser(getLoginUser().getId());
		art.setTitle(urltitle);
		art.setType(1);
		art.setProvinceid(Long.parseLong(urlproid));
		art.setIsdel(0);
		art.setContent(url);
		articleService.savearticle(art);
		return "redirect:/linkurl";
	}
	
	/**
	 * 保存文章
	 * */
	
	
	/**
	 * 点击下载文件
	 * 主要还是看要什么参数
	 * */
	@RequestMapping(value="/file/{k}", method=RequestMethod.GET)
	public void downloadfile(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		try {
			//k表示文件的id
			if (k!=null&&k.length()>0) {
				FilesInfo fileInfo = new FilesInfo();
				fileInfo.setId(Long.parseLong(k));
				fileInfo = filesInfoService.getFileInfoByID(fileInfo);
				String fileName = fileInfo.getName()== null ? "" : fileInfo.getName()+"."+fileInfo.getSuffix();
				File file = new File(fileInfo.getPath()+fileInfo.getNewname()+"."+fileInfo.getNewsuffix());
				fileName = URLEncoder.encode(fileName, "UTF-8"); 
				response.reset();  
			    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
			    response.addHeader("Content-Length", "" + file.length());  
			    response.setContentType("application/octet-stream;charset=UTF-8");
			    //以流的形式下载文件  
		        InputStream fis = new BufferedInputStream(new FileInputStream(file));  
		        byte[] buffer = new byte[fis.available()];  
		        fis.read(buffer);  
		        fis.close(); 
		        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
			    outputStream.write(buffer);  
			    outputStream.flush();  
			    outputStream.close(); 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 预览文件
	 * 主要还是看要什么参数
	 * */
	@RequestMapping(value="/viewfile/{k}", method=RequestMethod.GET)
	public void viewfile(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		try {
			//k表示文件的id
			if (k!=null&&k.length()>0) {
				
				
				
				
				
				FilesInfo fileInfo = new FilesInfo();
				fileInfo.setId(Long.parseLong(k));
				fileInfo = filesInfoService.getFileInfoByID(fileInfo);
				String fileName = fileInfo.getName()== null ? "" : fileInfo.getName()+"."+fileInfo.getSuffix();
				File file = new File(fileInfo.getPath()+fileInfo.getNewname()+"."+fileInfo.getNewsuffix());
				fileName = URLEncoder.encode(fileName, "UTF-8"); 
				
				
			        File imageFile = file;
			        if (imageFile.exists()) {
			            FileInputStream fis = null;
			            OutputStream os = null;
			            try {
			                fis = new FileInputStream(imageFile);
			                os = response.getOutputStream();
			                int count = 0;
			                byte[] buffer = new byte[1024 * 8];
			                while ((count = fis.read(buffer)) != -1) {
			                    os.write(buffer, 0, count);
			                    os.flush();
			                }

			            } catch (Exception e) {
			                e.printStackTrace();
			            } finally {
			                try {
			                    fis.close();
			                    os.close();
			                } catch (Exception e) {
			                    e.printStackTrace();
			                }
			            }

			        }
				
				
					/*
					 * response.reset(); ////inline是在线打开，attachment是下载；默认是inline
					 * //如果文件浏览器打不开，会自动转为attachment response.setHeader("Content-Disposition",
					 * "inline; filename=\"" + fileName + "\"");
					 * response.addHeader("Content-Length", "" + file.length());
					 * response.setContentType("application/octet-stream;charset=UTF-8");
					 * //以流的形式下载文件 InputStream fis = new BufferedInputStream(new
					 * FileInputStream(file)); byte[] buffer = new byte[fis.available()];
					 * fis.read(buffer); fis.close(); OutputStream outputStream = new
					 * BufferedOutputStream(response.getOutputStream()); outputStream.write(buffer);
					 * outputStream.flush(); outputStream.close();
					 */
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
	
	/**
	 * 保存客户预约信息
	 * @param info
	 * @param attr
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/customer/addcontactsdynamicinfo", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String addContactsDynamicInfo(@ModelAttribute ContactsDynamicInfo cdinfo,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes attr) throws Exception{
		
		String result ="1";
		//String msg = "预约成功!";
		try{
			 cdinfo.setState(0);
		     cdinfo.setCreateuser(getLoginUser().getId());
			if(StringUtils.isEmpty(cdinfo.getStime())){
				if(cdinfo.getId()==null||cdinfo.getId()<1){
					 cdinfo.setStime(CommonUtil.getDateAll(""));
					 cdinfo.setState(2); 
				}
				 //msg ="添加联系记录成功";
			 }
			 contactsDynamicInfoService.saveContactsDynamicInfo(cdinfo);
		}catch(Exception e){
			 result ="0";
		}
		return result;
	}
	
	/**
	 * 预约
	 * */
	@RequestMapping(value = "/customer/bookingcontactsdynamicinfo", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String bookingContactsDynamicInfo(String remark,String stime,String value,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes attr) throws Exception{
		
		ContactsDynamicInfo cdinfo = new ContactsDynamicInfo();
		cdinfo.setRemark(remark);
		cdinfo.setStime(stime);
		String key[] = value.split(",");
		String result ="1";
		//String msg = "预约成功!";
		try{
			cdinfo.setState(0);
		    cdinfo.setCreateuser(getLoginUser().getId());
			for (String kk : key) {
				cdinfo.setCusid(Long.parseLong(kk));
				contactsDynamicInfoService.saveContactsDynamicInfo(cdinfo);
			}
		}catch(Exception e){
			 result ="0";
		}
		return result;
	}
	
	
	
	
	
	
	/**
	 * 管理条件拼接<br>
	 * 现在具体条件还不是太清楚，<br>
	 * 先占位，等以后要加的再添加<br>
	 * 企业和人才的拼接先写到一起，<br>
	 * 因为不知道条件是不是一样的<br>
	 * */
	@RequestMapping(value = "/getmanageurl")
	public String getEnterpriseManagementUrl(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		String url; //ty{客户类型}_p{页码}_so{排列方式}_st{客户状态（所在库）}_pr{省份}_c{城市}_at{category}?kwd={关键字}
		if (ci.getType() != null && ci.getType() == 0) {
			//人才管理
			url = "/customer/entman/ty0";
		} else {
			//企业管理
			url = "/customer/entman/ty1";
		}
		url += "_p"+ getSkipToPage();
		if (ci.getSort() == null || ci.getSort() == "") {
			url += "_so0";
		} else {
			url += "_so"+ci.getSort();
		}
		if(ci.getSttime()!=null&&ci.getSttime().length()>0) {
			url += "_done"+ci.getSttime();
		}
		if(ci.getEntime()!=null&&ci.getEntime().length()>0) {
			url += "_dtwo"+ci.getEntime();
		}
		if (ci.getLxstate() != null && ci.getLxstate() >-1) {
			url += "_lx" + ci.getLxstate(); 
		}
		if (ci.getState() != null && ci.getState() >-1) {
			url += "_st" + ci.getState(); 
		}
		if (ci.getSource() != null && ci.getSource() >-1) {
			url += "_sr" + ci.getSource(); 
		}
		if (!Strings.isNullOrEmpty(ci.getProvince())){
			url +="_ro" + ci.getProvince();
		}
		
		if (!Strings.isNullOrEmpty(ci.getCategory())) {
			url +="_at" + ci.getCategory();
		}
		if (ci.getBoutique() !=null) {
			url +="_j" + ci.getBoutique();
		}
		url +="?";
		/*
		 ...
		 如果有其他条件就加到这里面
		 ...
		*/
		if (!Strings.isNullOrEmpty(ci.getKeyWord())){
			url += "&kwd=" + URLEncoder.encode(URLEncoder.encode(ci.getKeyWord(), "UTF-8"),"UTF-8");
		}
		if (!Strings.isNullOrEmpty(ci.getAddress())) {
			url +="&address=" +  URLEncoder.encode(URLEncoder.encode(ci.getAddress(), "UTF-8"),"UTF-8");;
		}
		return "redirect:" + url;
	}
	
	/**
	 * 参数转换<br>
	 * 将K中的参数取出放入map集合中
	 * */
	private static Map<String, Object> toBean(String k) {
		//ty{客户类型}_p{页码}_j{精品资源排列方式}_so{排列方式}_st{客户状态（所在库）}_c{城市}?kwd={关键字}
		Map<String, Object> map = new HashMap<String, Object>();
		String[] key = k.split("_");
		for (String ks : key) {
			if (ks.indexOf("ty")>-1){
				try{
					map.put("ty", Integer.parseInt(ks.replace("ty", "")));
				}catch(Exception e){}	
			} else if (ks.indexOf("p")>-1) {
				try{
					map.put("p", Integer.parseInt(ks.replace("p", "")));
				}catch(Exception e){}
			} else if (ks.indexOf("done")>-1) {
				try{
					map.put("dqtime", ks.replace("done", ""));
				}catch(Exception e){}
			}else if (ks.indexOf("dtwo")>-1) {
				try{
					map.put("dqtimetwo", ks.replace("dtwo", ""));
				}catch(Exception e){}
			} 
			else if (ks.indexOf("lx")>-1) {
				try{
					map.put("lx", Integer.parseInt(ks.replace("lx", "")));
				}catch(Exception e){}
			}
			else if (ks.indexOf("sr")>-1) {
				try{
					map.put("sr", Integer.parseInt(ks.replace("sr", "")));
				}catch(Exception e){}
			}
			else if (ks.indexOf("bz")>-1) {
				try{
					map.put("bz",  Integer.parseInt(ks.replace("bz", "")));
				}catch(Exception e){}
			}
			else if (ks.indexOf("so")>-1) {
				try{
					map.put("so", ks.replace("so", ""));
				}catch(Exception e){}
			}  else if (ks.indexOf("st")>-1) {
				try{
					map.put("st", Integer.parseInt(ks.replace("st", "")));
				}catch(Exception e){}
			} else if (ks.indexOf("ro")>-1) {
				try{
					map.put("ro", ks.replace("ro", ""));
				}catch(Exception e){}
			}  else if (ks.indexOf("c")>-1) {
				try{
					map.put("c", ks.replace("c", ""));
				}catch(Exception e){}
			} else if (ks.indexOf("at")>-1) {
				try{
					map.put("at", ks.replace("at", ""));
				}catch(Exception e){}
			} else if (ks.indexOf("j")>-1) {
				try{
					map.put("j",Integer.parseInt(ks.replace("j", "")));
				}catch(Exception e){}
			} 
			 
		}
		return map;
	}
	
	/**
	 * 企业管理页面<br>
	 * 根据参数K查询对应的customer列表<br>
	 * 根据state决定跳转到哪个页面<br>
	 * */
	@RequestMapping(value="/customer/qualificationusers", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getQualificationCustomerUserListByAjax(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		ci.setType(0);
		if(ci.getState()==null){
			ci.setState(-1);
		}
		if(ci.getUid()!=null&&ci.getUid()<0) {
			ci.setUid(null);
		}
		List<CustomerInfo> list = customerService.getQualificationCustomerList(ci, getSkipToPage(), pageSize);
		Pager  pager = new Pager();
		pager.setPageNo(getSkipToPage());
		pager.setPageSize(pageSize);
		pager.setResultList(list);
		return JSONArray.toJSONString(pager); 
	}
	
	@RequestMapping(value="/customer/guakaocustomerlist", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getGuakaoCustomerUserListByAjax(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		ci.setType(0);
		if(ci.getState()==null){
			ci.setState(-1);
		}
		if(ci.getUid()!=null&&ci.getUid()<0) {
			ci.setUid(null);
		}
		List<CustomerInfo> list = customerService.getGaokaoCustomerList(ci, getSkipToPage(), pageSize);
		Pager  pager = new Pager();
		pager.setPageNo(getSkipToPage());
		pager.setPageSize(pageSize);
		pager.setResultList(list);
		return JSONArray.toJSONString(pager); 
	}
	
	
	/**
	 * 企业管理页面<br>
	 * 根据参数K查询对应的customer列表<br>
	 * 根据state决定跳转到哪个页面<br>
	 * */
	@RequestMapping(value="/customer/userlist", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getCustomerUserListByAjax(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		ci.setType(0);
		if(ci.getState()==null){
			ci.setState(-1);
		}
		if(ci.getUid()!=null&&ci.getUid()<0) {
			ci.setUid(null);
		}
		//根据ci中的条件获取列表
		Pager pager = customerService.getContractCustomerList(ci, getSkipToPage(), pageSize);
		return JSONArray.toJSONString(pager); 
	}
	
	
	
	/**
	 * 管理条件拼接<br>
	 * 现在具体条件还不是太清楚，<br>
	 * 先占位，等以后要加的再添加<br>
	 * 企业和人才的拼接先写到一起，<br>
	 * 因为不知道条件是不是一样的<br>
	 * */
	@RequestMapping(value = "/getbizmanageurl")
	public String getEnterpriseManagementUrlBiz(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		String url = "/customer/bizentman/ty1";
		 
		url += "_p"+ getSkipToPage();
		if (ci.getSort() == null || ci.getSort() == "") {
			url += "_so0";
		} else {
			url += "_so"+ci.getSort();
		}
		if(ci.getSttime()!=null&&ci.getSttime().length()>0) {
			url += "_done"+ci.getSttime();
		}
		if(ci.getEntime()!=null&&ci.getEntime().length()>0) {
			url += "_dtwo"+ci.getEntime();
		}
		if (ci.getLxstate() != null && ci.getLxstate() >-1) {
			url += "_lx" + ci.getLxstate(); 
		}
		if (ci.getState() != null && ci.getState() >-1) {
			url += "_st" + ci.getState(); 
		}
		if (ci.getSource() != null && ci.getSource() >-1) {
			url += "_sr" + ci.getSource(); 
		}
		if (!Strings.isNullOrEmpty(ci.getProvince())){
			url +="_ro" + ci.getProvince();
		}
		if (ci.getBiztype()!=null && ci.getBiztype() >-1){
			url +="_bz" + ci.getBiztype();
		}
		
		if (!Strings.isNullOrEmpty(ci.getCategory())) {
			url +="_at" + ci.getCategory();
		}
		url +="?";
		/*
		 ...
		 如果有其他条件就加到这里面
		 ...
		*/
		if (!Strings.isNullOrEmpty(ci.getKeyWord())){
			url += "&kwd=" + URLEncoder.encode(URLEncoder.encode(ci.getKeyWord(), "UTF-8"),"UTF-8");
		}
		if (!Strings.isNullOrEmpty(ci.getAddress())) {
			url +="&address=" +  URLEncoder.encode(URLEncoder.encode(ci.getAddress(), "UTF-8"),"UTF-8");;
		}
		return "redirect:" + url;
	}
	
	/**
	 * 企业管理页面<br>
	 * 根据参数K查询对应的customer列表<br>
	 * 根据state决定跳转到哪个页面<br>
	 * */
	@RequestMapping("/customer/bizentman/{k}")
	public String bizEnterpriseManagePage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		UserAccount ua = getLoginUser();
		//创建一个Customer对象来接收参数
		CustomerInfo ci = new CustomerInfo();
		//获取参数集合
		Map<String, Object> map = toBean(k);
		//获取页码，定义每页显示多少（根据state决定）
		Integer pageNo = map.get("p") == null ? 1 : (Integer)map.get("p");
		Integer pageSize = 10;
		//给ci赋值
		ci.setType((Integer)map.get("ty"));
		if (map.get("lx")!=null && map.get("lx")!=""){
			ci.setLxstate((Integer)map.get("lx"));
		}
		if (!Strings.isNullOrEmpty((String)map.get("so"))){
			ci.setSort((String)map.get("so"));
		} else {
			ci.setSort("0");
		}
		if (map.get("st")!=null && map.get("st")!=""){
			ci.setState((Integer)map.get("st"));
		}
		if (map.get("dqtime")!=null && map.get("dqtime")!=""){
			ci.setSttime((String)map.get("dqtime"));
		}
		if (map.get("dqtimetwo")!=null && map.get("dqtimetwo")!=""){
			ci.setEntime((String)map.get("dqtimetwo"));
		}
		if (map.get("bz")!=null && map.get("bz")!=""){
			ci.setBiztype((Integer)map.get("bz"));
		}
		if (map.get("sr")!=null && map.get("sr")!=""){
			ci.setSource((Integer)map.get("sr"));
		}
		if (map.get("at")!=null && map.get("at")!=""){
			ci.setCategory((String)map.get("at"));
		}
		ci.setCity((String)map.get("c"));
		ci.setProvince((String)map.get("ro"));
		if(request.getParameter("kwd")!=null){  
			ci.setKeyWord(URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		
		if(request.getParameter("address")!=null){  
			ci.setAddress(URLDecoder.decode(URLDecoder.decode(request.getParameter("address"), "UTF-8"),"UTF-8"));
		}
		
		//ci赋值uid
		ci.setUid(ua.getId());
		//根据ci中的条件获取列表
		Pager pager = customerService.getCustomerByBiz(ci, pageNo, pageSize);
		pager.setUrl("/customer/bizentman/" + k);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord", ci.getKeyWord());
		params.put("sort",ci.getSort());
		params.put("city", ci.getCity());
		params.put("lxstate", ci.getLxstate());
		params.put("address", ci.getAddress());
		params.put("province", ci.getProvince());
		params.put("sttime", ci.getSttime());
		params.put("entime", ci.getEntime());
		params.put("province", ci.getProvince());
		params.put("state", ci.getState());
		params.put("source", ci.getSource());
		params.put("category", ci.getCategory());
		params.put("biztype", ci.getBiztype());
		params.put("boutique", ci.getBoutique());
		//要是有其他参数要继续往下添加
		pager.setParams(params);
		request.setAttribute("pager", pager);
		//我把企业和人才的相同的页面写到一起了，传到页面一个type来区分
		request.setAttribute("customertype", ci.getType());
		request.setAttribute("customerstate", ci.getState());
		//要向页面传省的值
		request.setAttribute("province", sysService.getProvinceList());
		//这里要根据state和type判断要跳转到哪个页面
		return "/customermanage/customerlist_biz";
	}
	/**
	 * 企业管理页面<br>
	 * 根据参数K查询对应的customer列表<br>
	 * 根据state决定跳转到哪个页面<br>
	 * */
	@RequestMapping("/customer/entman/{k}")
	public String intoEnterpriseManagePage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		UserAccount ua = getLoginUser();
		//创建一个Customer对象来接收参数
		CustomerInfo ci = new CustomerInfo();
		//获取参数集合
		Map<String, Object> map = toBean(k);
		//获取页码，定义每页显示多少（根据state决定）
		Integer pageNo = map.get("p") == null ? 1 : (Integer)map.get("p");
		Integer pageSize = 10;
		//给ci赋值
		ci.setType((Integer)map.get("ty"));
		if (map.get("lx")!=null && map.get("lx")!=""){
			ci.setLxstate((Integer)map.get("lx"));
		}
		if (!Strings.isNullOrEmpty((String)map.get("so"))){
			ci.setSort((String)map.get("so"));
		} else {
			ci.setSort("0");
		}
		if (map.get("st")!=null && map.get("st")!=""){
			ci.setState((Integer)map.get("st"));
		}
		if (map.get("dqtime")!=null && map.get("dqtime")!=""){
			ci.setSttime((String)map.get("dqtime"));
		}
		if (map.get("dqtimetwo")!=null && map.get("dqtimetwo")!=""){
			ci.setEntime((String)map.get("dqtimetwo"));
		}
		
		if (map.get("sr")!=null && map.get("sr")!=""){
			ci.setSource((Integer)map.get("sr"));
		}
		if (map.get("at")!=null && map.get("at")!=""){
			ci.setCategory((String)map.get("at"));
		}
		ci.setCity((String)map.get("c"));
		ci.setProvince((String)map.get("ro"));
		if(request.getParameter("kwd")!=null){  
			ci.setKeyWord(URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		
		if(request.getParameter("address")!=null){  
			ci.setAddress(URLDecoder.decode(URLDecoder.decode(request.getParameter("address"), "UTF-8"),"UTF-8"));
		}
		
		if (map.get("j")!=null && map.get("j")!=""){
			ci.setBoutique((Integer)map.get("j"));
		}
		
		if(ci.getState() !=null && ci.getState()==4) {
			ci.setBoutique(0);
		}
		
		//ci赋值uid
		ci.setUid(ua.getId());
		//根据ci中的条件获取列表
		Pager pager = customerService.getCustomerInfoList(ci, pageNo, pageSize);
		pager.setUrl("/customer/entman/" + k);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord", ci.getKeyWord());
		params.put("sort",ci.getSort());
		params.put("city", ci.getCity());
		params.put("lxstate", ci.getLxstate());
		params.put("address", ci.getAddress());
		params.put("province", ci.getProvince());
		params.put("sttime", ci.getSttime());
		params.put("entime", ci.getEntime());
		params.put("province", ci.getProvince());
		params.put("state", ci.getState());
		params.put("source", ci.getSource());
		params.put("category", ci.getCategory());
		params.put("boutique", ci.getBoutique());
		//要是有其他参数要继续往下添加
		pager.setParams(params);
		request.setAttribute("pager", pager);
		//我把企业和人才的相同的页面写到一起了，传到页面一个type来区分
		request.setAttribute("customertype", ci.getType());
		request.setAttribute("customerstate", ci.getState());
		//要向页面传省的值
		request.setAttribute("province", sysService.getProvinceList());
		//这里要根据state和type判断要跳转到哪个页面
		if (ci.getType() == 1) {
			if(ci.getState() != null && ci.getState() == 4) {
				return "/customermanage/customerlist_ggk";
			} else {
				return "/customermanage/customerlist_xsk";
			}
		} else {
			if(ci.getState() != null && ci.getState() == 4) {
				return "/resumemanage/resumelist_ggk";
			} else {
				return "/resumemanage/resumelist_xsk";
			}
		}
	}
	
	/**
	 * 录入客户 跳转到录入客户界面
	 * */
	@RequestMapping(value="/customer/addcustomer{k}")
	public String intoAddCustomerPage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		
		//k值是判断是录入企业还是人才
		request.setAttribute("type", k);
		//要向页面传省的值
		request.setAttribute("province", sysService.getProvinceList());
		//这是新增客户，所以客户id为null;
		request.setAttribute("customerid", null);
		request.setAttribute("curp", "156");
		//获取部门下所有人
	    List<UserInfo> userlist = userService.getAllUserListByDeptId(1L);
		request.setAttribute("userlist", userlist);
		if (k.equals("1")) {
			return "/customermanage/entercustomer";
		} else {
			return "/resumemanage/enterresume";
		}
		
	}
	
	/**
	 * 录入客户 保存客户信息 
	 * */
	@RequestMapping(value="/customer/savecustomer")
	@ResponseBody
	public String saveCustomer(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		/*
		 * 因为保存后下面还有东西要添加，所以用ajax
		 * 保存客户信息，有可能更改客户信息的时候也用这个controller
		 * 所以要加判断，看页面给回来的数据有没有id,有id是修改，没有id就是新增
		 * 然后还有一个是用户跟企业，type也是从页面传回来的 
		 * 然后就是保存或更新
		 * 最后将记录存到log
		 * */
		//最后要返回去的结果
		Long result = 0L;
		//如果不是公共库，标记在哪个使用者的库里
		//标记是修改还是新增
		int sign = 0;
		if (ci.getId() != null && ci.getId() > 0) {
			sign = 1;
		} else {
			if (ci.getState() != 4) {
				ci.setUid(getLoginUser().getId());
			}
			ci.setCreateuser(getLoginUser().getId());
		}
		if (ci.getCreatedate().length() < 1) {
			ci.setCreatedate(null);
		} 
		
		if(sign==0) {
			 
			//创建对象
			CustomerInfo cinfo = new CustomerInfo();
			cinfo.setState(ci.getState());
			cinfo.setUpdateuser(getLoginUser().getId());
			cinfo.setUid(getLoginUser().getId());
			cinfo.setType(ci.getType());
			//先判断该用户这个type中有多少资源
			int resourceCount = customerService.getResourceCount(cinfo);
			if (ci.getType() == 1 && resourceCount >= getLoginUser().getInfo().getMaxcustom()) {
				return JSON.toJSONString(-1);
			} 
			if (ci.getType() == 0 && resourceCount >= getLoginUser().getInfo().getMaxresume()) {
				return JSON.toJSONString(-1);
			}
			
			
		}
		
		
		ci = customerService.saveCustomerInfo(ci);
		if (ci!=null) {
			result = ci.getId();
		}
		
		return JSON.toJSONString(result);
	}
	
	/**
	 * 录入客户 保存客户联系人信息
	 * */
	@RequestMapping(value="/customer/savecustomercontacts",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveCustomerOther(@ModelAttribute CustomerContacts cc,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		if (cc.getId() != null && cc.getId() != 0) {
			//修改
			cc = customerContactsService.updateCustomerContacts(cc);
		} else {
			//新增
			cc = customerContactsService.insertCustomerContacts(cc);
		}
		//这里要更新一下企业联系人
		customerService.updatecustomertel(cc.getId(),cc.getCusid());
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", cc.getName());
		map.put("phone", cc.getPhone());
		map.put("qq", cc.getQq());
		map.put("id", cc.getId().toString());
		map.put("cusid", cc.getCusid().toString());
		map.put("webchart", cc.getWebchart());
		return JSON.toJSONString(map);
	}
	
	
	/**
	 * 设置主要联系人
	 * */
	@RequestMapping(value="/customer/savemaincustomercontacts",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveMainCustomerContacts(@ModelAttribute CustomerContacts cc,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		int result = customerContactsService.saveMainContacts(cc);
		return JSON.toJSONString(result);
	}
	
	
	
	/**
	 * 录入客户 上传并保存附件
	 *i{id}_t{type}
	 *type表示是从哪个页面来的 0是修改页面 1是详细信息页面
	 * */
	@RequestMapping(value="/customer/uploadCustomerfile{k}")
	public String uploadCustomerfile(@RequestParam MultipartFile[] file,@PathVariable String k,String remark,String filetype,Integer btype,Long fileid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		
		String key[] = k.split("_");
		Long id = 0L;
		 int type = 0;
		for (String kk : key) {
			if (kk.indexOf("i") > -1) {
				id = Long.parseLong(kk.replace("i", ""));
			} else if (kk.indexOf("t") > -1) {
				type = Integer.parseInt(kk.replace("t", ""));
			}
		}
		List<MultipartFile> files = Arrays.asList(file);
		List<FilesInfo> list = filesInfoService.saveFile(files);
		CustomerFiles cf = new CustomerFiles();
		cf.setCusid(id);
		cf.setType(btype);
		if (!Strings.isNullOrEmpty(remark)) {
			cf.setRemark(remark);
		}
		for (FilesInfo fi : list) {
			if (fi != null && fi.getId() != null) {
				cf.setFileid(fi.getId());
				/*
				 * if (filetype != null) { cf.setType(Integer.parseInt(filetype)); }
				 */
				if (fileid != null && fileid > 0 ) {
					//修改
					cf.setId(fileid); 
					cf = customerFilesService.updateCustomerFiles(cf);
				} else {
					//新增
					cf = customerFilesService.insertCustomerFiles(cf);
				}
			}
		}
		if (type == 0) {
			return "redirect:/customer/updatecustomer"+id;
		} else {
			return "redirect:/customer/customerinfo1/c"+id;
		}
	}
	
	
	/**
	 * 录入客户 保存联系人需求（附加修改需求）
	 * */
	@RequestMapping(value="/customer/savecustomercategory",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveCustomerCategory(@ModelAttribute CustomerCategory cc,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		cc.setCreateuser(getLoginUser().getId());
		if (cc.getId() != null && cc.getId() != 0) {
			//说明是修改
			cc = CustomerCategoryService.updateCustomerCategory(cc);
		} else {
			//说明是新增
			cc = CustomerCategoryService.insertCustomerCategory(cc);
		}
		
		
		CustomerInfo ci = new CustomerInfo();
		ci.setId(cc.getCusid());
		customerService.updateCustomerCategory(ci);
		/*
		 * 因为是用ajax动态加载，所以这里数据要改变一下，给传一个map集合回去
		 * 页面上要展示的数据有：
		 * 证书类型  性质 用途 备注 操作
		 * 证书类型，性质 用途 在数据库里都是数字
		 * */
		Integer category = cc.getCategory();
		Integer type = cc.getTypes();
		Integer paperspurpose = cc.getPaperspurpose();
		String remark = cc.getRemark();
		//创建一个map对象用于存放数据
		Map<String, String> map = new HashMap<String, String>();
		map.put("type", CrmUtil.getNameByTypesId(type));
		if (paperspurpose != null) {
			map.put("paperspurpose", CrmUtil.getNameByPaperspurposeId(paperspurpose));
		}
		map.put("remark", remark);
		try {
			map.put("category", sysService.getCategoryByid(category.toString(), "build_category").getName());
		}catch(Exception e) {
		}
		map.put("id", cc.getId().toString());
		return JSON.toJSONString(map);
	}
	
	/**
	 * 根据id获取客户资质需求
	 * */
	@RequestMapping(value="/customer/getcustomercategory",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getCustomerCategoryByCategoryId(String ids,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		Long id = Long.parseLong(ids);
		CustomerCategory cc = CustomerCategoryService.getCustomerCategoryById(id);
		Map<String, String> map = new HashMap<String, String>();
		map.put("category",cc.getCategory().toString());
		map.put("type", cc.getTypes().toString());
		if (cc.getPaperspurpose() != null) {
			map.put("paperspurpose", cc.getPaperspurpose().toString());
		}
		map.put("remark", cc.getRemark());
		return JSON.toJSONString(map);
	}
	
	/**
	 * 根据id获取客户联系人信息
	 * */
	@RequestMapping(value="/customer/getCustomerContact",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getCustomerContactByContactId(String ids,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		long id = Long.parseLong(ids);
		CustomerContacts cc = customerContactsService.getCustomerContactsById(id);
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", cc.getName());
		map.put("phone", cc.getPhone());
		map.put("fax", cc.getFax());
		map.put("mail", cc.getMail());
		map.put("qq", cc.getQq());
		map.put("job", cc.getJob());
		map.put("remark", cc.getRemark());
		map.put("id", cc.getId().toString());
		map.put("webchart", cc.getWebchart());
		return JSON.toJSONString(map);
	}
	
	/**
	 * 检测唯一标识符，企业名称是否已经存在
	 * */
	@RequestMapping(value="/customer/checkisexist")
	@ResponseBody
	public String checkfirmisexist(String value,int types,Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		String cname = null;
		String firm = null;
		
		if (types == 1) {
			cname = value; 
		} else if (types == 2) {
			firm = value;
		}
		
		CustomerInfo ci = new CustomerInfo();
		ci.setId(id);
		ci.setCname(cname);
		ci.setFirm(firm);
		ci.setType(1);
		int i = customerService.getCustomerInfoVerifyCount(ci);
		return JSON.toJSONString(i);
	}
	
	/**
	 * 检查用户手机号或电话是否已经存在
	 * */
	@RequestMapping(value="/customer/chaecktelisexist")
	@ResponseBody
	public String checkphoneortelisexist(String phone,String id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		CustomerContacts cc = new CustomerContacts();
		if (id != null && id != "" ) {
			cc.setCusid(Long.parseLong(id));
		}
		cc.setTel(phone);
		int i = customerContactsService.gettelcount(cc);
		return JSON.toJSONString(i);
	}
	
	
	
	/**
	 * 客户信息修改页面
	 * */
	@RequestMapping(value="/customer/updatecustomer{k}")
	public String updateCustomerinfo(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//先要获取信息表的id
		Long id = Long.parseLong(k);
		//获取部门下所有人
	    List<UserInfo> userlist = userService.getAllUserListByDeptId(1L);
		request.setAttribute("userlist", userlist);
		//然后就是根据信息表id获取信息详情了（里面包含了联系人表）
		CustomerInfo ci = customerService.getCustomerInfoById(id);
		
		if (ci.getType() == 0) {
			List<CustomerCategory> ccatlist = ci.getCategoryItem();
			List<CustomerContacts> cconlist = ci.getContactsItem();
			CustomerCategory ccat = new CustomerCategory();
			CustomerContacts ccon = new CustomerContacts();
			if (ccatlist.size() > 0) {
				ccat = ccatlist.get(0);
			}
			if (cconlist.size() > 0) {
				ccon = cconlist.get(0);
			}
			request.setAttribute("ccat", ccat);
			request.setAttribute("ccon", ccon);
		}
		
		//在公共库不能修改的情况下
		if (!getLoginUser().getId().equals(ci.getUid()) && ci.getState() != 4) {
			String uid = getLoginUser().getId().toString();
			String xzuser = ci.getXzuser();
			if(StringUtils.isEmpty(xzuser) || xzuser.indexOf(uid)<0) {
				//说明不是你的客户
				return "redirect:/customer/entman/ty"+ci.getType()+"_st"+ci.getState();
			} 
		}
		
		//现在要知道联系记录 还要知道预约情况 然后还要带分页...
		ContactsDynamicInfo cdinfo = new ContactsDynamicInfo();
		cdinfo.setCusid(id);
		cdinfo.setState(2);
		Integer pageNo1 = 1;
		Integer pageSize = 5;
		List<ContactsDynamicInfo> lxlist = contactsDynamicInfoService.getAllcdinfolist(cdinfo, pageNo1, pageSize);
		Pager lxpager = new Pager(pageNo1, pageSize);
		lxpager.setResultList(lxlist);
		request.setAttribute("lxpager", lxpager);
		
		cdinfo.setState(0);
		cdinfo.setCreateuser(getLoginUser().getId());
		List<ContactsDynamicInfo> yylist = contactsDynamicInfoService.getAllcdinfolist(cdinfo, pageNo1, pageSize);
		Pager yypager = new Pager(pageNo1, pageSize);
		yypager.setResultList(yylist);
		request.setAttribute("yypager", yypager);
		/*
		 * 想想有什么参数...
		 * 判断是企业还是人才的type
		 * 信息表的id
		 * 然后就是获取信息表
		 * 因为是修改 所以type从信息表中就能知道
		 * */
		request.setAttribute("type", ci.getType());
		request.setAttribute("state", ci.getState());
		//要向页面传省的值
		request.setAttribute("province", sysService.getProvinceList());
		//这是修改客户
		request.setAttribute("customerid", id);
		//然后就是把对象传到页面
		request.setAttribute("cuinfo", ci);
		
		if (ci.getType() == 1) {
			return "/customermanage/entercustomer";
		} else {
			return "/resumemanage/enterresume";
		}
	}
	
	
	//查看客户详情（最大权限）
	@RequestMapping(value="/customer/findcustomer{k}")
	public String findCustomerinfo(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//先要获取信息表的id
		Long id = Long.parseLong(k);
		//然后就是根据信息表id获取信息详情了（里面包含了联系人表）
		CustomerInfo ci = customerService.getCustomerInfoById(id);
		
		//获取部门下所有人
	    List<UserInfo> userlist = userService.getAllUserListByDeptId(1L);
		request.setAttribute("userlist", userlist);
		
		if (ci.getType() == 0) {
			List<CustomerCategory> ccatlist = ci.getCategoryItem();
			List<CustomerContacts> cconlist = ci.getContactsItem();
			CustomerCategory ccat = new CustomerCategory();
			CustomerContacts ccon = new CustomerContacts();
			if (ccatlist.size() > 0) {
				ccat = ccatlist.get(0);
			}
			if (cconlist.size() > 0) {
				ccon = cconlist.get(0);
			}
			request.setAttribute("ccat", ccat);
			request.setAttribute("ccon", ccon);
		}
		
		//现在要知道联系记录 还要知道预约情况 然后还要带分页...
		ContactsDynamicInfo cdinfo = new ContactsDynamicInfo();
		cdinfo.setCusid(id);
		cdinfo.setState(2);
		Integer pageNo1 = 1;
		Integer pageSize = 5;
		List<ContactsDynamicInfo> lxlist = contactsDynamicInfoService.getAllcdinfolist(cdinfo, pageNo1, pageSize);
		Pager lxpager = new Pager(pageNo1, pageSize);
		lxpager.setResultList(lxlist);
		request.setAttribute("lxpager", lxpager);
		
		cdinfo.setState(0);
		cdinfo.setCreateuser(getLoginUser().getId());
		List<ContactsDynamicInfo> yylist = contactsDynamicInfoService.getAllcdinfolist(cdinfo, pageNo1, pageSize);
		Pager yypager = new Pager(pageNo1, pageSize);
		yypager.setResultList(yylist);
		request.setAttribute("yypager", yypager);
		/*
		 * 想想有什么参数...
		 * 判断是企业还是人才的type
		 * 信息表的id
		 * 然后就是获取信息表
		 * 因为是修改 所以type从信息表中就能知道
		 * */
		request.setAttribute("type", ci.getType());
		request.setAttribute("state", ci.getState());
		//要向页面传省的值
		request.setAttribute("province", sysService.getProvinceList());
		//这是修改客户
		request.setAttribute("customerid", id);
		//然后就是把对象传到页面
		request.setAttribute("cuinfo", ci);
		
		if (ci.getType() == 1) {
			return "/customermanage/entercustomer1";
		} else {
			return "/resumemanage/enterresume1";
		}
	}
	
	
	
	
	
	/**
	 * 客户详情 （客户详情）
	 * k:c{客户id}
	 * */
	@RequestMapping(value="/customer/customerinfo1/{k}")
	public String getCustomerinfo1(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		/*
		 * 客户详情只要查处来客户的详情和联系人列表就行了
		 * 
		 * */
		Long cid = 0L;
		String[] key = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("c")>-1){
				cid = Long.parseLong(kk.replace("c", ""));
			}
		}
		if (cid == 0 || cid == null) {
			//说明不存在要跳到哪个页面没想好
		}
		//根据cid获取客户详情
		CustomerInfo customer = customerService.getCustomerInfoById(cid);
		request.setAttribute("customer", customer);
		request.setAttribute("userid", getLoginUser().getId());
		//跳转到相应页面
		if (customer.getType() == 1) {
			return "/customermanage/customerinfo1";
		} else {
			return "/resumemanage/resumeinfo1";
		}
	}
	
	
	/**
	 * 客户详情 （客户详情）
	 * k:c{客户id}
	 * */
	@RequestMapping(value="/customer/customerinfoajax", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getCustomerinfo1(@ModelAttribute CustomerInfo cinfo,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		cinfo.setCreateuser(getLoginUser().getId());
		//根据cid获取客户详情
		 List<CustomerContacts> contacts =customerContactsService.getAllCustomerContactsId(cinfo.getId());
		 cinfo.setContactsItem(contacts);
		//CustomerInfo customer = customerService.getCustomerInfoConttactsById(cinfo);
		return JSONArray.toJSONString(cinfo);
	}
	
	/**
	 * 客户详情（最大权限）
	 * */
	@RequestMapping(value="/customer/customerinfoajax1", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getCustomerinfo2(@ModelAttribute CustomerInfo cinfo,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		cinfo.setCreateuser(getLoginUser().getId());
		//根据cid获取客户详情
		CustomerInfo customer = customerService.getCustomerInfoById1(cinfo);
		return JSONArray.toJSONString(customer);
	}
	
	
	/**
	 * 联系记录
	 * */
	@RequestMapping(value="/customer/customerdynamic", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getCustomerinfo2(@ModelAttribute ContactsDynamicInfo cdinfo,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		cdinfo.setState(2);//已联系
		List<ContactsDynamicInfo> lxlist = contactsDynamicInfoService.getAllcdinfolist(cdinfo, getSkipToPage(), 5);
		Map<String,List<ContactsDynamicInfo>> map = new HashMap();
		map.put("list", lxlist);
		return JSONArray.toJSONString(map);
	}
	
	
	/**
	 * 客户详情（操作记录）
	 * k:c{客户id}_p{页码}?kwd={关键字}
	 * */
	@RequestMapping(value="/customer/customerinfo3/{k}")
	public String getCustomerinfo3(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		/*
		 * 操作记录要获取用户的操作记录
		 * */
		Long cid = 0L;
		Integer pageNo = 1;
		Integer pageSize = 10;
		String[] key = k.split("_");
		String keyword = null;
		for (String kk : key) {
			if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p", ""));
			} else if (kk.indexOf("c") > -1) {
				cid = Long.parseLong(kk.replace("c", ""));
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyword = URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8");
		}
		
		Log log = new Log();
		log.setContentid(cid);
		if (keyword != null) {
			log.setKeyWord(keyword);
		}
		List<Log> list = sysService.getLogList(log, getSkipToPage(), pageSize);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("kwd", keyword);
		Pager pager = new Pager();
		pager.setPageNo(pageNo);
		pager.setPageSize(pageSize);
		pager.setResultList(list);
		pager.setParams(params);
		pager.setUrl("/customer/customerinfo3/" + k);
		request.setAttribute("pager", pager);
		request.setAttribute("customerid", cid);
		return "/customermanage/customerinfo3";
	}
	
	/**
	 * 升级客户状态
	 * */
	@RequestMapping(value = "/customer/updatecustomerstate",method=RequestMethod.POST)
	@ResponseBody
	public String updateCustomerState(String value,String state,String type,String cname,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		//创建对象
		CustomerInfo cinfo = new CustomerInfo();
		cinfo.setState(Integer.parseInt(state));
		cinfo.setUpdateuser(getLoginUser().getId());
		cinfo.setUid(getLoginUser().getId());
		cinfo.setType(Integer.parseInt(type));
		//先判断该用户这个type中有多少资源
		int resourceCount = customerService.getResourceCount(cinfo);
		if (Integer.parseInt(type) == 1 && resourceCount >= getLoginUser().getInfo().getMaxcustom()) {
			return JSON.toJSONString(-1);
		} 
		if (Integer.parseInt(type) == 0 && resourceCount >= getLoginUser().getInfo().getMaxresume()) {
			return JSON.toJSONString(-1);
		}
		
		Log log = new Log();
		//这里我改了，现在只有获取客户会经过这里，改变客户状态没经过这里。2017/4/21
		if (cinfo.getState() == 4) {
			//判断客户是企业还是个人
			if (Integer.parseInt(type)==0) {
				log.setDescription("获取人才"+cname);
				log.setCategory(Constants.LOGCATEGORY.ZERO);
			} else {
				log.setDescription("获取企业客户"+cname);
				log.setCategory(Constants.LOGCATEGORY.ONE);
			}
			cinfo.setState(1);
		}
		/*switch (cinfo.getState()) {
		case 1:
			log.setDescription("升级客户到跟踪库");
			cinfo.setState(2);
			break;
		case 2:
			log.setDescription("升级客户到意向库");
			cinfo.setState(3);
			break;
		case 3:
			log.setDescription("升级客户到合作库");
			cinfo.setState(5);
			break;
		case 4:
			log.setDescription("获取客户");
			
			break;	
		default:
			log.setDescription("放弃客户");
			cinfo.setState(4);
			cinfo.setUid(0L);
			break;
		}*/
		//value里面包含一个或多个id
		int  i=0;
		if (!Strings.isNullOrEmpty(value)){
			//迭代器批量操作更新
			Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(value);
	        for (String idStr : splitStr) {
	        	   cinfo.setId(Long.parseLong(idStr));
	        		log.setContentid(cinfo.getId());
	        		log.setState(Constants.LOGSTATE.ZERO);
	        		log.setCreateuser(cinfo.getUpdateuser());
	        		log.setUid(cinfo.getUpdateuser());
	        		log.setOid(cinfo.getUpdateuser());
	                customerService.updateCustomerState(cinfo,log);
	                i++;
	        }
	        return JSON.toJSONString(i);
		} else {
			return JSON.toJSONString(0);
		}
	}
	
	
	/**
	 * 降级客户状态（废弃）
	 */
	/*@RequestMapping(value = "/customer/updatecustomerstatetwo", method = RequestMethod.POST)
	@ResponseBody
	public String updateCustomerStatetwo(String value,String state,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		CustomerInfo cinfo = new CustomerInfo();
		cinfo.setState(Integer.parseInt(state));
		cinfo.setUpdateuser(getLoginUser().getId());
		cinfo.setUid(getLoginUser().getId());
		Log log = new Log();
		switch (cinfo.getState()) {
		case 3:
			log.setDescription("降级到跟踪库");
			cinfo.setState(2);
			break;
		case 2:
			log.setDescription("降级到线索库");
			cinfo.setState(1);
			break;	
		case 1:
			log.setDescription("放弃客户");
			cinfo.setState(4);
			break;	
		default:
			log.setDescription("放弃客户");
			cinfo.setState(4);
			cinfo.setUid(0L);
			break;
		}
		
		//value里面包含一个或多个id
		if (!Strings.isNullOrEmpty(value)){
			//迭代器批量操作更新
			Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(value);
	        for (String idStr : splitStr) {
	        	   cinfo.setId(Long.parseLong(idStr));
	        		log.setContentid(cinfo.getId());
	        		log.setCategory(Constants.LOGCATEGORY.ONE);
	        		log.setCreateuser(cinfo.getUpdateuser());
	        		log.setUid(cinfo.getUpdateuser());
	                customerService.updateCustomerState(cinfo,log);
	        }
	        return JSON.toJSONString(1);
		} else {
			return JSON.toJSONString(0);
		}
	}*/
	
	/**
	 * 放弃客户状态
	 */
	@RequestMapping(value = "/customer/updatecustomerstateignore", method = RequestMethod.POST)
	@ResponseBody
	public String updateCustomerStateIgnore(String value,String state,String type,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
		RedirectAttributes redirectAttributes) throws Exception{
		
		CustomerInfo cinfo = new CustomerInfo();
		cinfo.setUpdateuser(getLoginUser().getId());
		cinfo.setState(4);
		cinfo.setUid(null);
		
		//value里面包含一个或多个id
		if (!Strings.isNullOrEmpty(value)){
			if (value.split(",").length > 1 || Integer.parseInt(type) == 1) {
				//迭代器批量操作更新
				Iterable<String> splitStr = Splitter.on(",").trimResults().omitEmptyStrings().split(value);
		        for (String idStr : splitStr) {
		        	   cinfo.setId(Long.parseLong(idStr));
		        	   String cname = customerService.getCustomerInfoById(Long.parseLong(idStr)).getCname();
		        	   Log log = new Log();
		        	   if (Integer.parseInt(type) == 0) {
		        		   log.setDescription("放弃人才"+cname);
		        		   log.setCategory(Constants.LOGCATEGORY.ZERO);
		        	   } else {
		        		   log.setDescription("放弃企业客户"+cname);
		        		   log.setCategory(Constants.LOGCATEGORY.ONE);
		        	   }
		        	   log.setContentid(cinfo.getId());
		        	   log.setState(Constants.LOGSTATE.ONE);
		        	   log.setCreateuser(cinfo.getUpdateuser());
		        	   log.setUid(cinfo.getUpdateuser());
		        	   log.setOid(cinfo.getUpdateuser());
		               customerService.updateCustomerState(cinfo,log);
		        }
			} else {
				//这里是被放弃的单个的个人用户，要加一个判断，是否有合同，如果有合同的话，就不能被放弃
				//那就要从合同表里查是否有记录
				int result = contractService.checkResurmeHaveContract(Long.parseLong(value));
				if (result > 0) {
					return JSON.toJSONString(2);
				} else {
					 cinfo.setId(Long.parseLong(value));
		        	   String cname = customerService.getCustomerInfoById(Long.parseLong(value)).getCname();
		        	   Log log = new Log();
		        	   if (Integer.parseInt(type) == 0) {
		        		   log.setDescription("放弃人才"+cname);
		        		   log.setCategory(Constants.LOGCATEGORY.ZERO);
		        	   } else {
		        		   log.setDescription("放弃企业客户"+cname);
		        		   log.setCategory(Constants.LOGCATEGORY.ONE);
		        	   }
		        	   log.setContentid(cinfo.getId());
		        	   log.setState(Constants.LOGSTATE.ONE);
		        	   log.setCreateuser(cinfo.getUpdateuser());
		        	   log.setUid(cinfo.getUpdateuser());
		        	   log.setOid(cinfo.getUpdateuser());
		               customerService.updateCustomerState(cinfo,log);
				}
			}
	        return JSON.toJSONString(1);
		} else {
			return JSON.toJSONString(0);
		}
	}
	
	
	/**
	 * 员工资源转移url拼接
	 * */
	@RequestMapping(value="/customer/transurl")
	public String gettransformurl(String uid,String type,String boutique,String state,String keyWord,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/customer/transform";
		url += "p"+getSkipToPage();
		if (uid != null && uid.length() > 0) {
			url += "_u"+uid;
		}
		if (type != null && type.length() > 0) {
			url += "_t"+type;
		}
		if (state != null && state.length() > 0) {
			url += "_s"+state;
		}
		if (boutique != null && boutique.length() > 0) {
			url += "_j"+boutique;
		}
		if (!Strings.isNullOrEmpty(keyWord)){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(keyWord, "UTF-8"),"UTF-8");
		}
		return "redirect:"+url;
	}
	
	
	/**
	 * 查询企业
	 * k: u{uid}_t{type}_p{page}
	 * */
	@RequestMapping(value="/customer/customerlist")
	@ResponseBody
	public Object customerlist(RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		/**
		 * 能看这个的应该是部门负责人，
		 * 点开资源转移之后，他可以看到所有他部门下的人的资源
		 * 页面会展示第一个人的所有资源，然后他可以选择部门下的人，
		 * 或者选择类别
		 * 所以要先获取这个人所在部门，然后获取他部门下的所有用户id
		 * 然后再获取第一个人的资源
		 * */
		//基本条件
		Integer pageNo = getSkipToPage();
		Integer pageSize = 10;
		String uid = (String)request.getParameter("uid");
		String type = (String)request.getParameter("type");
		Long deptid = getLoginUser().getInfo().getDeptid();
		String state = (String)request.getParameter("state");
		String keyWord = request.getParameter("kwd");;
		 
		
		//获取部门下所有人
		List<UserInfo> userlist = userService.getAllUserListByDeptId(deptid);
		//创建一个用户对象
		CustomerInfo info = new CustomerInfo();
		//判断要显示哪个人
		/*if (uid == 0 && userlist.size() > 0) {
			//说明没有指定的人
			uid = userlist.get(0).getUid();
		}*/
		if (StringUtils.isNotEmpty(uid)) {
			info.setUid(Long.parseLong(uid));
		}
		if (StringUtils.isNotEmpty(type)) {
			info.setType(Integer.parseInt(type));
		}
		if (StringUtils.isNotEmpty(state)) {
			info.setState(Integer.parseInt(state));
		}
		if (StringUtils.isNotEmpty(keyWord)) {
			info.setKeyWord(keyWord);
		}
		List<Long> dpsonlist = sysService.getAllDeptmentidByPid(deptid);
		info.setSondpidlist(dpsonlist);
		
		
		//因为跟多页转移共用一个service所以这个搬到外面来了
		info.setStartsize((pageNo-1)*pageSize);
		info.setEndsize(pageSize);
		List<CustomerInfo> list = customerService.transformlist(info, pageNo, pageSize);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uid", uid);
		params.put("type",type);
		params.put("state",state);
		params.put("keyWord",keyWord);
	 
		return list;
	}
	
	
	
	/**
	 * 员工资源转移页面
	 * k: u{uid}_t{type}_p{page}
	 * */
	@RequestMapping(value="/customer/transform{k}")
	public String transform(@PathVariable String k,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		/**
		 * 能看这个的应该是部门负责人，
		 * 点开资源转移之后，他可以看到所有他部门下的人的资源
		 * 页面会展示第一个人的所有资源，然后他可以选择部门下的人，
		 * 或者选择类别
		 * 所以要先获取这个人所在部门，然后获取他部门下的所有用户id
		 * 然后再获取第一个人的资源
		 * */
		//基本条件
		Integer pageNo = getSkipToPage();
		Integer pageSize = 10;
		Long uid = 0L;
		Integer type = null;
		Long deptid = getLoginUser().getInfo().getDeptid();
		Integer state = null;
		String keyWord = null;
		Integer boutique = null;
		
		
		//对获取到的参数进行分解
		String key[] = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("u") > -1) {
				uid = Long.parseLong(kk.replace("u", ""));
			} else if (kk.indexOf("t") > -1) {
				type = Integer.parseInt(kk.replace("t", ""));
			} else if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p", ""));
			} else if (kk.indexOf("s") > -1) {
				state = Integer.parseInt(kk.replace("s", ""));
			}else if (kk.indexOf("j") > -1) {
				boutique = Integer.parseInt(kk.replace("j", ""));
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		
		//获取部门下所有人
		List<UserInfo> userlist = userService.getAllUserListByDeptId(deptid);
		//创建一个用户对象
		CustomerInfo info = new CustomerInfo();
		//判断要显示哪个人
		/*if (uid == 0 && userlist.size() > 0) {
			//说明没有指定的人
			uid = userlist.get(0).getUid();
		}*/
		if (uid != null && uid > 0L) {
			info.setUid(uid);
		}
		if (type != null && type != -1) {
			info.setType(type);
		}
		if (state != null && state != -1) {
			info.setState(state);
		}
		if (keyWord != null) {
			info.setKeyWord(keyWord);
		}
		if(boutique  != null && boutique != -1) {
			info.setBoutique(boutique);
		}
		//List<Long> dpsonlist = sysService.getAllDeptmentidByPid(deptid);
		//info.setSondpidlist(dpsonlist);
		
		
		//因为跟多页转移共用一个service所以这个搬到外面来了
		info.setStartsize((pageNo-1)*pageSize);
		info.setEndsize(pageSize);
		List<CustomerInfo> list = customerService.transformlist(info, pageNo, pageSize);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uid", uid);
		params.put("type",type);
		params.put("state",state);
		params.put("boutique",boutique);
		params.put("keyWord",keyWord);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setParams(params);
		pager.setResultList(list);
		pager.setUrl("/customer/transform"+k);
		request.setAttribute("pager", pager);
		request.setAttribute("userlist", userlist);
		
		return "/customermanage/transform";
	}
	
	/**
	 * 企业资源管理
	 * k: u{uid}_t{type}_p{page}
	 * */
	@RequestMapping(value="/customer/customermanageform{k}")
	public String customerManageform(@PathVariable String k,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		/**
		 * 能看这个的应该是部门负责人，
		 * 点开资源转移之后，他可以看到所有他部门下的人的资源
		 * 页面会展示第一个人的所有资源，然后他可以选择部门下的人，
		 * 或者选择类别
		 * 所以要先获取这个人所在部门，然后获取他部门下的所有用户id
		 * 然后再获取第一个人的资源
		 * */
		//基本条件
		Integer pageNo = getSkipToPage();
		Integer pageSize = 10;
		Long uid = 0L;
		Integer type = 1;
		Long deptid = getLoginUser().getInfo().getDeptid();
		Integer state = null;
		String keyWord = null;
		String paperspurpose  = request.getParameter("paperspurpose");
		
		
		//对获取到的参数进行分解
		String key[] = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("u") > -1) {
				uid = Long.parseLong(kk.replace("u", ""));
			} else if (kk.indexOf("t") > -1) {
				type = 1;//Integer.parseInt(kk.replace("t", ""));
			} else if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p", ""));
			} else if (kk.indexOf("s") > -1) {
				state = Integer.parseInt(kk.replace("s", ""));
			}
		}
		if(StringUtils.isNotEmpty(request.getParameter("keyWord"))){  
			keyWord =request.getParameter("keyWord");
		}
		
		if(StringUtils.isNotEmpty(request.getParameter("uid"))){  
			Long uidtemp = Long.parseLong(request.getParameter("uid"));
			if(uidtemp>0) {
				uid = uidtemp;
			}
		}
		
		if(StringUtils.isNotEmpty(request.getParameter("state"))){  
			int stateTemp = Integer.parseInt(request.getParameter("state"));
			if(stateTemp>0) {
				state = stateTemp;
			}
		}
		 
		
		//获取部门下所有人
		List<UserInfo> userlist = userService.getAllUserListByDeptId(deptid);
		//创建一个用户对象
		CustomerInfo info = new CustomerInfo();

		if(StringUtils.isNotEmpty(paperspurpose)) {
			if (Integer.parseInt(paperspurpose) > -1) {
				info.setPaperspurpose(Integer.parseInt(paperspurpose));
			}
		}
		
		
		//判断要显示哪个人
		/*if (uid == 0 && userlist.size() > 0) {
			//说明没有指定的人
			uid = userlist.get(0).getUid();
		}*/
		if (uid != null && uid > 0L) {
			info.setUid(uid);
		}
		if (type != null && type != -1) {
			info.setType(type);
		}
		if (state != null && state != -1) {
			info.setState(state);
		}
		if (keyWord != null) {
			info.setKeyWord(keyWord);
		}
		List<Long> dpsonlist = sysService.getAllDeptmentidByPid(deptid);
		info.setSondpidlist(dpsonlist);
		
		
		//因为跟多页转移共用一个service所以这个搬到外面来了
		info.setStartsize((pageNo-1)*pageSize);
		info.setEndsize(pageSize);
		List<CustomerInfo> list = customerService.transformlist(info, pageNo, pageSize);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uid", uid);
		params.put("type",type);
		params.put("state",state);
		params.put("paperspurpose",paperspurpose);
		params.put("keyWord",keyWord);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setParams(params);
		pager.setResultList(list);
		pager.setUrl("/customer/customermanageform"+k);
		request.setAttribute("pager", pager);
		request.setAttribute("userlist", userlist);
		
		return "/customermanage/customermanage";
	}
	
	
	/**
	 * 资源核对查询
	 * k是type用于标记是企业还是简历
	 * */
	@RequestMapping(value="/customer/checkcustomer{k}")
	public String checkCustomer(@ModelAttribute CustomerInfo ci,@PathVariable String k,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		if(ci!=null&&StringUtils.isNotEmpty(ci.getKeyWord())){
			List<CustomerInfo> result =customerService.getCustomerByKeyWord(ci, getSkipToPage(), 10);
			Pager pager = new Pager();
			pager.setPageNo(getSkipToPage());
			pager.setPageSize(pageSize);
			pager.setResultList(result);
			request.setAttribute("pager", pager);  
			//request.setAttribute("result", pager);
			request.setAttribute("param", ci);
		}
		//获取当前时间
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowdate = sdf.format(date);
		request.setAttribute("nowdate", nowdate);
		request.setAttribute("province", sysService.getProvinceList());
		request.setAttribute("customertype", k);
		return "/customermanage/customer_check";
	}
	
	/**
	 * 删除文件
	 * */
	@RequestMapping(value="/customer/deletefileinfo")
	@ResponseBody
	public String deleteFileinfo(String id,RedirectAttributes attr,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		int result = customerFilesService.deleteCustomerFiles(Long.parseLong(id));
		return JSON.toJSONString(result);
	}
	
	/**
	 * 根据联系记录获取五条联系记录
	 * */
	@RequestMapping(value="/customer/customercontactsbycusid", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getCustomerContactsByCusid(String id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		Integer pageNo = 1;
		Integer pageSize = 5;

		ContactsDynamicInfo cdinfo = new ContactsDynamicInfo();
		cdinfo.setCusid(Long.parseLong(id));
		cdinfo.setState(2);
		List<ContactsDynamicInfo> list = contactsDynamicInfoService.getAllcdinfolist(cdinfo, pageNo, pageSize);
		return JSON.toJSONString(list);
	}
	
	/**
	 * 根据用户的id获取证书和类型的拼接
	 * */
	@RequestMapping(value="/customer/customercategoryandtypes",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getCustomerCategoryAndTypes(String id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		List<CustomerCategory> cuscatlist = CustomerCategoryService.getCustomerCatrgoryByCustomerId(Long.parseLong(id));
		List<String> Stringlist = new ArrayList<String>();
		for (CustomerCategory ccat : cuscatlist) {
			String value = ccat.getCategory().toString();
			String name = "build_category";
			ConfigureItem   cf2 = sysService.getConfigureItemByValue(value.substring(0,2)+"000",name);
			String showname = cf2.getName()+"-";
			ConfigureItem   cf1 = sysService.getConfigureItemByValue(value,name);
			showname  += cf1.getName();
			String cate = showname + "/" + CrmUtil.getNameByTypesId(ccat.getTypes());
			Stringlist.add(cate);
		}
		return JSON.toJSONString(Stringlist);
	}
	
	
	
	/**
	 * 删除联系人
	 * */
	@RequestMapping(value="/customer/deletecustomercontactsbyid")
	@ResponseBody
	public String deleteCustomerContactsById(@ModelAttribute CustomerContacts cc,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		cc.setIsdel(1);
		cc = customerContactsService.updateCustomerContacts(cc);
		//这里要更新一下企业联系人
		customerService.updatecustomertel(cc.getId(),cc.getCusid());
		return JSON.toJSONString(0);
	}
	
	
	/**
	 * 删除需求
	 * */
	@RequestMapping(value="/customer/deletecustomercategorybyid")
	@ResponseBody
	public String deletecustomercategorybyid(@ModelAttribute CustomerCategory cc,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		cc.setIsdel(1);
		cc = CustomerCategoryService.updateCustomerCategory(cc);
		customerService.updatecustomercategory(cc.getId(),cc.getCusid());
		return JSON.toJSONString(0);
	}
	
	
	/**
	 * 资源转移，转移一个或多个
	 * */
	@RequestMapping(value="/customer/transcusoneorsome")
	@ResponseBody
	public String transformCustomerOneOrSome(String cusids,String uid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		String cusidarr[] = cusids.split(",");
		for (String cusid : cusidarr) {
			if (cusid != null && cusid.length() > 0) {
				customerService.updatecustomeruid(getLoginUser().getId(),Long.parseLong(uid), Long.parseLong(cusid),getLoginUser().getId(),-1);
			}
		}
		return JSON.toJSONString(1);
	}
	
	
	
	/**
	 * 资源转移，转移多页
	 * */
	@RequestMapping(value="/customer/transcusmore")
	@ResponseBody
	public String transformCustomerCustomoerMore(String startpage,String endpage,String uid,String pagesize,String type,String olduid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//要根据页数跟每页的数据数得出总转移条数
		/*
		 * 开始转移的是起始页,要是起始页跟结束页一样 那就转移那一页 也就是endpage-startpage+1
		 * */
		
		Integer pageNo = Integer.parseInt(startpage);
		Integer pageSizes = Integer.parseInt(pagesize)*(Integer.parseInt(endpage)-Integer.parseInt(startpage)+1);
		//创建一个用户对象
		CustomerInfo info = new CustomerInfo();
		info.setSort("99"); //随机拉取资源
		if (olduid == null || olduid.length() < 1) {
			return JSON.toJSONString(0);
		} else {
			info.setUid(Long.parseLong(olduid));
		}
		if (type != null && type.length() > 0 && Integer.parseInt(type) != -1) {
			info.setType(Integer.parseInt(type));
		}
		//先放startsize和endsize
		info.setStartsize((pageNo-1)*Integer.parseInt(pagesize));
		info.setEndsize(pageSizes);
		List<CustomerInfo> list = customerService.transformlist(info, pageNo, Integer.parseInt(pagesize));
		if (uid != null && uid.length() > 0) {
			for (CustomerInfo ci : list) {
				customerService.updatecustomeruid(getLoginUser().getId(),Long.parseLong(uid), ci.getId(),getLoginUser().getId(),Integer.parseInt(type));
			}
		} else {
			return JSON.toJSONString(0);
		}
		return JSON.toJSONString(1);
	}
	
	/**
	 * 资源转移，转移全部
	 * */
	@RequestMapping(value="/customer/transcusall")
	@ResponseBody
	public String transformCustomerCustomerAll(String uid, String olduid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		
		/*转移全部，把一个人的数据转移给另一个人
		  contentid 就是 crm_customer_info 中的id
		  description是拼接
		  oid 是接收转移的人id
	      uid 是被转移人的id
		  state 是转移对应的state
		  category 根据crm_customer_info 决定
		  要先存log再改要不然记录就没了...
		*/
		Log log = new Log();
		log.setUid(Long.parseLong(olduid));
		log.setOid(Long.parseLong(uid));
		log.setState(Constants.LOGSTATE.FIVE);
		log.setCreateuser(getLoginUser().getId());
		sysService.insertAllTransLog(log);
		
		CustomerInfo ci = new CustomerInfo();
		ci.setUid(Long.parseLong(uid));
		ci.setOlduid(Long.parseLong(olduid));
		customerService.transformcustomerall(ci);
		
		return JSON.toJSONString(1);
	}
	
	/**
	 * 资源转移，根据类型获取页数
	 * */
	@RequestMapping(value="/customer/allpagenobytype")
	@ResponseBody
	public String getAllPageNoByType(String uid,String type,String pagesize,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		CustomerInfo ci = new CustomerInfo();
		ci.setUid(Long.parseLong(uid));
		if (type != null && Integer.parseInt(type) != -1) {
			ci.setType(Integer.parseInt(type));
		}
		int result = customerService.getCustomerInfoTotalSizeByParams(ci);
		int totalPages = result % Integer.parseInt(pagesize) == 0 ? (result / Integer.parseInt(pagesize)) : (result / Integer.parseInt(pagesize) + 1);
		return JSON.toJSONString(totalPages);
	}
	
	/**
	 * 进入用户客户统计页面
	 * */
	@RequestMapping(value = "/customer/customerstatistics")
	public String intoCustomerStatistics(String uid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		/**
		 * 如果uid!=null&&uid!=-1说明页面中选中人了,就要查这个人的具体信息,否则就查所有的人的
		 * */
		CustomerInfo cif = new CustomerInfo();
		UserInfo uif = null;
		if (uid != null && Integer.parseInt(uid) > 0) {
			uif = userService.getUserByid(Long.parseLong(uid));
			cif.setType(1);
			cif.setUid(Long.parseLong(uid));
			uif.setNowcustom(customerService.getResourceCount(cif));
			cif.setType(0);
			uif.setNowresume(customerService.getResourceCount(cif));
		}
		
		//获取当前用户的部门id
		Long deptid = getLoginUser().getInfo().getDeptid();
		//获取部门下所有人
		List<UserInfo> userlist = userService.getAllUserListByDeptId(deptid);
		CustomerInfo ci = new CustomerInfo();
		for (UserInfo ui : userlist) {
			ci.setType(1);
			ci.setUid(ui.getUid());
			ui.setNowcustom(customerService.getResourceCount(ci));
			ci.setType(0);
			ui.setNowresume(customerService.getResourceCount(ci));
			
			ui.setCurrentEcount(0);
			ui.setCurrentPcount(0);
			//获取已录入客户和简历
			List<CustomerInfo> lrkhlist = customerService.getCustomerInfoListByTypes(1, ui.getUid(), 1, 1);
			if(lrkhlist!=null&&lrkhlist.size()>0) {
				ui.setCurrentEcount(lrkhlist.get(0).getTotalResults());
			}
			List<CustomerInfo> lrjllist = customerService.getCustomerInfoListByTypes(2, ui.getUid(), 1, 1);
			if(lrjllist!=null&&lrjllist.size()>0) {
				ui.setCurrentPcount(lrjllist.get(0).getTotalResults());
			} 
		}
		request.setAttribute("userlist", userlist);
		request.setAttribute("uid",uid);
		request.setAttribute("uif", uif);
		
		return "/customermanage/statistics";
	}
	
	/**
	 * 更改用户资源限制
	 * */
	@ResponseBody
	@RequestMapping(value="/customer/changeresourcerestrict")
	public String changeUserResourceRestrict(String uid,String maxcustomcount,String maxresumecount,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		Pattern pattern = Pattern.compile("[0-9]*"); 
		Matcher isNum1 = pattern.matcher(maxcustomcount);
		Matcher isNum2 = pattern.matcher(maxresumecount);
		if( !isNum1.matches() || !isNum2.matches() ){
			return JSON.toJSONString(-1);
		} 
		UserInfo ui = new UserInfo(Long.parseLong(uid));
			ui.setMaxcustom(Integer.parseInt(maxcustomcount));
			ui.setMaxresume(Integer.parseInt(maxresumecount));
		int result = userService.updateUserInfo(ui);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 资源日志url拼接
	 * */
	@RequestMapping(value="/customer/resourceslogurl")
	public String getResourcesLogUrl(String state,String category,String keyWord,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "/customer/resourceslog";
		url += "p"+getSkipToPage();
		if (state != null && state.length() > 0) {
			url += "_s" + state;
		} 
		if (category != null && category.length() > 0) {
			url += "_c" + category;
		}
		if (!Strings.isNullOrEmpty(keyWord)){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(keyWord, "UTF-8"),"UTF-8");
		}
		return "redirect:"+url;
	}
	
	/**
	 * 进入资源日志页面
	 * 资源日志可以查看当前用户所有放弃的，获取的，索要的（预留），分配的（预留）记录
	 * 从crm_log表中根据state来判断记录类别，根据category来判断是人才还是企业
	 * */
	@RequestMapping(value="/customer/resourceslog{k}")
	public String intoResourcesLogPage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		Integer pageNo = 1;
		Integer pageSize = 10;
		Integer state = null;
		Integer type = null;
		String keyWord = null;
		
		Log log = new Log();
		//oid是当前登录用户
		log.setOid(getLoginUser().getId());
		String key[] = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p",""));
			} else if (kk.indexOf("s") > -1) {
				state = Integer.parseInt(kk.replace("s", ""));
			} else if (kk.indexOf("c") > -1) {
				type = Integer.parseInt(kk.replace("c", ""));
			}
		}
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			log.setKeyWord(keyWord);
		}
		if (state != null && state > -1) {
			log.setState(state);
		}
		if (type != null && type > -1) {
			log.setCategory(type);
		}
		//根据条件获取对应的loglist
		List<Log> resultList = sysService.getLogList(log, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(resultList);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("state", state);
		params.put("category", type);
		params.put("keyWord", keyWord);
		pager.setParams(params);
		request.setAttribute("pager", pager);
		return "/customermanage/resourcelog";
	}
	
	/**
	 * 客服管理URL拼接
	 * _t{type}_p{page}_s{servicesign}?kwd={kwd}
	 * */
	@RequestMapping(value="/customer/servicemanageurl")
	public String ServiceManageUrl(String keyWord,String type,String servicesign,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "/customer/servicemanage";
		url += "p"+getSkipToPage();
		if (type != null && type.length() > 0) {
			url += "_t"+ type;
		}
		if (servicesign != null && servicesign.length() > 0) {
			url += "_s"+ servicesign;
		}
		if (!Strings.isNullOrEmpty(keyWord)){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(keyWord, "UTF-8"),"UTF-8");
		}
		return "redirect:"+url;
	}
	
	
	/**
	 * 客服管理
	 * 2017/8/4更新
	 * 更改查询条件,查询成熟等级为合作客户的客户
	 * 原始:
	 * 查已添加收款的企业和个人，可搜索，可以更新联系记录，可以更新信息
	 * */
	@RequestMapping(value="/customer/servicemanage{k}")
	public String intoServiceManagePage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		Integer pageNo = 1;
		Integer type = -1;
		Integer servicesign = -2;
		String keyWord = null;
		
		String key[] = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p",""));
			} else if (kk.indexOf("t") > -1) {
				type = Integer.parseInt(kk.replace("t", ""));
			} else if (kk.indexOf("s") > -1) {
				servicesign = Integer.parseInt(kk.replace("s", ""));
			}
		}
		if(request.getParameter("kwd")!=null){
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		
		//要查询所有成熟等级为合作客户的客户,同时要关联合同表,客服联系记录表
		//原先页面显示的信息有:编号,合作方,合作方类型合同金额,合同状态,签订时间,所属人
		//因为现在改变了查询方式,显示的内容要改一下 客户名称 所属人 合同状态 签订时间 
		
		//创建对象
		CustomerInfo ci = new CustomerInfo();
		//传参
		ci.setType(type);
		ci.setKeyWord(keyWord);
		ci.setServicesign(servicesign);
		//获取列表
		List<CustomerInfo> list = customerService.getCustomerServiceListByParams(ci, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		pager.setUrl("/customer/servicemanage");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", type);
		params.put("keyWord", keyWord);
		params.put("servicesign", servicesign);
		pager.setParams(params);
		request.setAttribute("pager", pager);
		return "/customermanage/servicemanage";
	}
	
	/**
	 * 查询标记
	 * */
	@RequestMapping(value="/customer/checkservicesign",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String checkServiceSign(String cusid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		CusService cs = new CusService();
		cs.setCusid(Long.parseLong(cusid));
		cs = cusSerService.getCsByCusid(cs);
		return JSON.toJSONString(cs);
		
	}
	
	/**
	 * 添加更新标记
	 * */
	@RequestMapping(value="/customer/saveservicesign")
	@ResponseBody
	public String saveServiceSign(String cusid,String state,String remark,String id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		CusService cs = new CusService();
		cs.setCusid(Long.parseLong(cusid));
		cs.setCreateuser(getLoginUser().getId());
		cs.setState(Integer.parseInt(state));
		cs.setRemark(remark);
		cs.setIsdel(0);
		if (id != null && id.length() > 0 && Long.parseLong(id) != 0) {
			//说明是更新
			//传入id
			cs.setId(Long.parseLong(id));
		} 
		cusSerService.saveCusService(cs);
		return JSON.toJSONString(0);
	}
	
	
	/**
	 * 代办事项url拼接
	 * 关键字 审批状态 合同(签或没签)
	 * */
	@RequestMapping(value="/customer/commissionlisturl")
	public String intoCommissionListUrl(String keyWord,String state, String consign,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "/customer/commissionlist";
		url += "p"+getSkipToPage();
		if (state != null && state.length() > 0) {
			url += "_s"+ state;
		}
		if (consign != null && consign.length() > 0) {
			url += "_c"+ consign;
		}
		if (!Strings.isNullOrEmpty(keyWord)){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(keyWord, "UTF-8"),"UTF-8");
		}
		return "redirect:"+url; 
	}
	
	
	/**
	 * 进入代办事项列表页
	 * */
	@RequestMapping(value="/customer/commissionlist{k}")
	public String intoCommissionListPage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		Integer pageNo = getSkipToPage();
		Integer pageSize = 10;
		String keyWord = null;
		Integer state = null;
		Integer consign = null;
		
		String key[] = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p",""));
			} else if (kk.indexOf("s") > -1) {
				state = Integer.parseInt(kk.replace("s", ""));
			} else if (kk.indexOf("c") > -1) {
				consign = Integer.parseInt(kk.replace("c", ""));
			}
		}
		if(request.getParameter("kwd")!=null){
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		
		//获取代办建造师列表
		CommissionCustomer cc = new CommissionCustomer();
		cc.setCreateuser(getLoginUser().getId());
		cc.setKeyWord(keyWord);
		if(state != null){
			cc.setState(state);
		}
		if (consign != null) {
			cc.setConsign(consign);
		}
		
		List<CommissionCustomer> list = commissionCustomerService.getAllComCusListByParams(cc, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		pager.setUrl("/customer/commissionlist");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("state", state);
		params.put("consign", consign);
		params.put("keyWord", keyWord);
		pager.setParams(params);
		request.setAttribute("pager", pager);
		request.setAttribute("uid", getLoginUser().getId());
		
		return "/customermanage/Commissionlist";
	}
	
	/**
	 * 保存代办事项
	 * */
	@RequestMapping(value="/customer/savecommission")
	@ResponseBody
	public String saveCommission(@ModelAttribute Commission c,@RequestParam("cids") Long cids[],@RequestParam("uids") Long uids[],HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		//所以第一步是把获取的代办存到数据库
		//将审批状态设置为0
		c.setApprovestate(0);
		c.setCreateuser(getLoginUser().getId());
		c.setCreateuserName(getLoginUser().getInfo().getName());
		//保存代办事项
		c = commissionService.saveCommission(c);
		//获取了代办事项的id之后,把受理的建造师存到受理建造师表中
		CommissionCustomer cc = new CommissionCustomer();
		cc.setComid(c.getId());
		cc.setIsdel(0);
		cc.setConid(0); //没合同时,合同id设为0
		for (Long cid : cids) {
			cc.setCusid(cid);
			//每个建造师单独保存
			commissionCustomerService.saveCommissionCustomer(cc);
		}
		return JSON.toJSONString(1);
	}
	
	/**
	 * 代办事项详情页
	 * c中只有id
	 * */
	@RequestMapping(value="/customer/commissioninfo")
	public String CommissionInfo(@ModelAttribute CommissionCustomer cc,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
			
		Commission c = new Commission();
		c.setId(cc.getComid());
		c = commissionService.getcommissionInfoById(c);
		request.setAttribute("commission", c);
		
		return "/customermanage/commissioninfo";
	}
	
	/**
	 * 提交审批
	 * */
	@RequestMapping(value="/customer/approvecommission")
	@ResponseBody
	public String approveCommission(Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception  {
		int result = 0;
		Commission c = new Commission();
		c.setId(id);
		c = commissionService.getcommissionInfoById(c);
		c.setCreateuserName(getLoginUser().getInfo().getName());
		result = commissionService.approveCommission(c);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 删除建造师
	 * */
	@RequestMapping(value="/customer/deletecomcus")
	@ResponseBody
	public String deleteCommissionCustomer(Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		int result = 0;
		CommissionCustomer cc = new CommissionCustomer();
		cc.setId(id);
		cc.setIsdel(1);
		result = commissionCustomerService.updateCCinfo(cc);
		return JSON.toJSONString(result);
	}
	
	
	/**
	 * 待挂资源URL拼接
	 * p{page}?kwd={keyword}&add={address}
	 * @throws Exception 
	 * */
	@RequestMapping(value="/customer/waitforanchoredurl")
	public String waitForAnchoredUrl(String keyWord,String address,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		String url = "/customer/waitforanchored";
		url += "p"+getSkipToPage();
		if (!Strings.isNullOrEmpty(keyWord)&&!Strings.isNullOrEmpty(address)){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(keyWord, "UTF-8"),"UTF-8")+"&add="+URLEncoder.encode(URLEncoder.encode(address, "UTF-8"),"UTF-8");
		} else if (Strings.isNullOrEmpty(keyWord)&&!Strings.isNullOrEmpty(address)){
			url += "?add=" + URLEncoder.encode(URLEncoder.encode(address, "UTF-8"),"UTF-8");
		} else if (!Strings.isNullOrEmpty(keyWord)&&Strings.isNullOrEmpty(address)){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(keyWord, "UTF-8"),"UTF-8");
		}
		
		System.out.println(url);
		
		return "redirect:"+url;
	}
	
	
	/**
	 * 待挂资源
	 * 2017/7/24添加
	 * 展示所有已通过审批的垫款资源
	 * @throws Exception 
	 * */
	@RequestMapping(value="/customer/waitforanchored{k}")
	public String waitForAnchored(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		//定义参数
				Integer pageNo = getSkipToPage();
				Integer pageSize = 20;
				String kwd = null;
				String add = null;
				//获取参数
				String key[] = k.split("_");
				for (String kk : key) {
					if (kk.indexOf("p") > -1) {
						pageNo = Integer.parseInt(kk.replace("p",""));
					}
				}
				if(request.getParameter("kwd")!=null){
					kwd = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
				}
				if(request.getParameter("add")!=null){
					add = (URLDecoder.decode(URLDecoder.decode(request.getParameter("add"), "UTF-8"),"UTF-8"));
				}
				
				CustomerInfo info = new CustomerInfo();
				info.setKeyWord(kwd);
				info.setAddress(add);
				
				int totlamoney = customerService.getAllwaitForAnchoredMoney(info);
				
				Pager pager = new Pager(pageNo, pageSize);
				List<CustomerInfo> list = customerService.getAllwaitForAnchoredList(info, pageNo, pageSize);
				pager.setResultList(list);
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("address", add);
				params.put("keyWord", kwd);
				pager.setParams(params);
				request.setAttribute("pager", pager);
				request.setAttribute("totlamoney", totlamoney);
				return "/customermanage/waitforanchored";
	}
	
	/**
	 * 2017/7/25添加
	 * 根据cusid获取所有标记为原件的文件列表
	 * */
	@RequestMapping(value="/customer/getcusfilelistbycusid",produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getCusFileListByCusid(String id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		CustomerFiles cf = new CustomerFiles();
		cf.setCusid(Long.parseLong(id));
		//cf.setType(1);
		//根据条件获取列表
		List<CustomerFiles> list = customerFilesService.getCusFilListByParams(cf);
		return JSON.toJSONString(list);
	}
	
	
	
	/**
	 * 2017/7/27添加
	 * 资源分配列表页面
	 * */
	@RequestMapping(value="/customer/customertemplist")
	public String CustomerTempList(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		int pageNo = getSkipToPage();
		int pageSize = 10;
		CustomerInfoTemp cit = new CustomerInfoTemp();
		//获取所有未分配列表
		List<CustomerInfoTemp> list = customerInfoTempService.getAllCustomerInfoTempList(cit, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		request.setAttribute("pager", pager);
		
		//获取当前用户部门id
		Long deptid = getLoginUser().getInfo().getDeptid();
		//获取该部门下所有成员
		List<UserInfo> userlist = userService.getAllUserListByDeptId(deptid);
		request.setAttribute("userlist", userlist);
		return "/customermanage/customertemp";
	}
	
	/**
	 * 分配全部资源
	 * */
	@RequestMapping(value="/customer/distributionall")
	@ResponseBody
	public String distributionAll(String uid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//获取当前登录用户id
		Long loginuid = getLoginUser().getId();
		/*
		 * 将所有临时资源的uid改为设定的uid
		 * 更新的时候,要看看有没有与临时资源电话号码相同的客户资源
		 * 如果有就将临时资源的cusid设置成客户资源的id
		 * */
		CustomerInfoTemp cit = new CustomerInfoTemp();
		//根据条件获取临时资源表
		List<CustomerInfoTemp> list = customerInfoTempService.getAllCustomerInfoTempList(cit, null, null);
		bindAndSaveCustomer(Long.parseLong(uid), list,loginuid);
		return JSON.toJSONString(0);
	}
	
	
	/**
	 * 分配部分资源(多页)
	 * */
	@RequestMapping(value="/customer/distributionsome")
	@ResponseBody
	public String distributionSome(String startpage,String endpage,String uid,String pagesize,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//获取当前登录用户id
		Long loginuid = getLoginUser().getId();
		//要根据页数跟每页的数据数得出总分配条数
		/*
		 * 开始转移的是起始页,要是起始页跟结束页一样 那就分配那一页 也就是endpage-startpage+1
		 * */
		Integer pageNo = Integer.parseInt(startpage);
		Integer pageSizes = Integer.parseInt(pagesize)*(Integer.parseInt(endpage)-Integer.parseInt(startpage)+1);
		CustomerInfoTemp cit = new CustomerInfoTemp();
		cit.setSort("99"); //随机拉取资源
		//根据条件获取临时资源表
		List<CustomerInfoTemp> list = customerInfoTempService.getAllCustomerInfoTempList(cit, pageNo, pageSizes);
		bindAndSaveCustomer(Long.parseLong(uid), list,loginuid);
		return JSON.toJSONString(0);
	}
	
	/**
	 * 分配一个或多个资源
	 * */
	@RequestMapping(value="/customer/distributiononeorsome")
	@ResponseBody
	public String distributionOneOrSome (String cusids,String uid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		
		//获取当前登录用户id
		Long loginuid = getLoginUser().getId();
		//分割
		String cusidarr[] = cusids.split(",");
		//定义list接收结果
		List<CustomerInfoTemp> list = new ArrayList<CustomerInfoTemp>();
		CustomerInfoTemp cit = new CustomerInfoTemp();
		for (String cusid : cusidarr) {
			if (cusid != null && cusid.length() > 0) {
				cit = customerInfoTempService.getCusInfoTempById(Long.parseLong(cusid));
				if (cit != null) {
					list.add(cit);
				}
			}
		}
		bindAndSaveCustomer(Long.parseLong(uid), list,loginuid);
		return JSON.toJSONString(0);
	}
	
	
	
	/**
	 * 分配并绑定资源的公共方法
	 * uid:分配给谁
	 * list:分配的列表
	 * loginuid:操作人id(当前登录用户)
	 * */
	private void bindAndSaveCustomer(Long uid,List<CustomerInfoTemp> list,Long loginuid){
		int i=0;
		//循环判断是否符合绑定要求
		for (CustomerInfoTemp c : list) {
			//存入要保存人的uid
			c.setUid(uid);
			//根据tel绑定
			if (c.getTel() != null) {
				customerInfoTempService.bindCustomer(c,loginuid);
				i++;
			}
		}
		if(i>0){
			//添加操作日志
			Log log = new Log();
		    log.setCategory(Constants.LOGCATEGORY.ONE);
			log.setDescription("获取临时客户"+i+"条");
			log.setState(Constants.LOGSTATE.ZERO);
			log.setCreateuser(uid);
			log.setUid(uid);
			log.setOid(uid);
			sysService.insertLog(log);
		}
	}
	
	/**
	 * 删除资源(数据库删)
	 * */
	@RequestMapping(value="/customer/deletecustomertemp")
	@ResponseBody
	public String deletecustomertemp(String id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		CustomerInfoTemp c = new CustomerInfoTemp();
		c.setId(Long.parseLong(id));
		customerInfoTempService.delete(c);
		return JSON.toJSONString(0);
	}
	
	/**
	 * 分配资源url拼接
	 * */
	@RequestMapping(value="/customer/customerresourcesurl")
	public String customerResourcesUrl(String keyWord,String address,String servicesign,String state,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/customer/customerresources";
		url += "p"+getSkipToPage();
		if (servicesign != null && servicesign.length() > 0) {
			url += "_s"+ servicesign;
		}
		if (state != null && state.length() > 0) {
			url += "_c"+ state;
		}
		if (!Strings.isNullOrEmpty(keyWord)){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(keyWord, "UTF-8"),"UTF-8");
			if (!Strings.isNullOrEmpty(address)){
				url += "&address=" + URLEncoder.encode(URLEncoder.encode(address, "UTF-8"),"UTF-8");
			}
		}else{
			if (!Strings.isNullOrEmpty(address)){
				url += "?address=" + URLEncoder.encode(URLEncoder.encode(address, "UTF-8"),"UTF-8");
			}
		}
		
		
		return "redirect:"+url;
	}
	
	
	/**
	 * 分配资源页面
	 * */
	@RequestMapping(value="/customer/customerresources{k}")
	public String customerResources(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		Integer pageNo = 1;
		Integer pageSize = 10;
		Integer servicesign = -2;
		Integer state=null;
		String keyWord = null;
		String address =null;
		
		String key[] = k.split("_");
		for (String kk : key) {
			if (kk.indexOf("p") > -1) {
				pageNo = Integer.parseInt(kk.replace("p",""));
			} else if (kk.indexOf("s") > -1) {
				servicesign = Integer.parseInt(kk.replace("s", ""));
			} else if (kk.indexOf("c") > -1) {
				state = Integer.parseInt(kk.replace("c", ""));
			}
		}
		if(request.getParameter("kwd")!=null){
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		if(request.getParameter("address")!=null){
			address = (URLDecoder.decode(URLDecoder.decode(request.getParameter("address"), "UTF-8"),"UTF-8"));
		}
		//获取当前用户id
		Long uid = getLoginUser().getId();
		//获取分配给他的列表
		CustomerInfoTemp cit = new CustomerInfoTemp();
		cit.setUid(uid);
		cit.setKeyWord(keyWord);
		cit.setAddress(address);
		cit.setState(state);
		cit.setServicesign(servicesign);
		List<CustomerInfoTemp> list = customerInfoTempService.getListByParams(cit, pageNo, pageSize);
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(list);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("keyWord", keyWord);
		params.put("address", address);
		params.put("servicesign", servicesign);
		params.put("state", state);
		pager.setParams(params);
		
		request.setAttribute("pager", pager);
		
		//获取当前时间
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowdate = sdf.format(date);
		request.setAttribute("nowdate", nowdate);
		
		return "/customermanage/customeresources";
	}
	
	/**
	 * 删除资源(isdel删)
	 * 删除后,将资源放回公共库
	 * 2017/8/15更新
	 * 原本id只有一个,现在可能有多个,需要对id进行循环
	 * */
	@RequestMapping(value="/customer/deletecustemp")
	@ResponseBody
	public String deletecustemp(String ids,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		CustomerInfoTemp c = new CustomerInfoTemp();
		//对ids进行处理
		String idsvalue[]  = ids.split(",");
		for (String id : idsvalue) {
			c.setId(Long.parseLong(id));
			//先获取资源信息
			c = customerInfoTempService.getCusInfoTempById(Long.parseLong(id));
			c.setIsdel(1);
			/*c.setServicesign(99);//删除后的状态 没有实际意义   恢复到资源库里
			c.setUid(99L);*/
			c.setRemark("");
			
			//判断uid和cusid
			//删除有两种情况:未分配时删除和已分配后删除,未分配删除不用改什么,已分配后删除把分配的资源放回公共库
			//已分配的还有三种情况:1有cusid,uid是自己2有cusid,uid不是自己3:没有cusid
			//情况1将cusid放到公共库.情况2,3不变
			/*if (c.getUid()!= null && c.getUid() == getLoginUser().getId() && c.getCusid() != null) {
				//将cusid对应的客户放入公共库
				CustomerInfo cinfo = new CustomerInfo();
				cinfo.setUpdateuser(getLoginUser().getId());
				cinfo.setState(4);
				cinfo.setUid(null);
				cinfo.setId(c.getCusid());
				String cname = customerService.getCustomerInfoById(c.getCusid()).getCname();
				Log log = new Log();
				log.setDescription("放弃人才简历"+cname);
	 		   	log.setCategory(Constants.LOGCATEGORY.ZERO);
	 		    log.setContentid(cinfo.getId());
	    	    log.setState(Constants.LOGSTATE.ONE);
	    	    log.setCreateuser(cinfo.getUpdateuser());
	    	    log.setUid(cinfo.getUpdateuser());
	    	    log.setOid(cinfo.getUpdateuser());
	            customerService.updateCustomerState(cinfo,log);
			}*/
			customerInfoTempService.update(c);
		}
		return JSON.toJSONString(0);
	}
	
	/**
	 * 录入客户(临时转为正式)
	 * */
	@RequestMapping(value="/customer/changetemptocustomer{k}")
	public String ChangeTempToCustomer(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//获取临时客户
		CustomerInfoTemp cif = customerInfoTempService.getCusInfoTempById(Long.parseLong(k));
		//创建一个正式客户
		CustomerInfo ci = cif;
		CustomerContacts cc = new CustomerContacts();
		
		//ci.setc
		//将临时客户中的信息放到正式客户中
		//根据excel中的内容来:姓名 备用名 联系电话 报考专业 地址 成熟等级 qq 微信 身份证号 客户来源 客户分类 备注
		//因为已经分配过 所以成熟等级默认设置为
		if(ci.getState()==null||ci.getState()!=0){
			ci.setState(1);
		}
		ci.setType(0);
		if (cif.getTel() != null) {
			cc.setTel(cif.getTel());
			cc.setPhone(cif.getTel());
		}
		if (cif.getQq() != null) {
			cc.setQq(cif.getQq());
		}
		if (cif.getWebchart() != null) {
			cc.setWebchart(cif.getWebchart());
		}
		
		request.setAttribute("cuinfo", ci);
		request.setAttribute("ccon", cc);
		request.setAttribute("type", 0);
		request.setAttribute("state", ci.getState());
		
		return "/resumemanage/enterresume";
	}
	
	/**
	 * 临时客户添加标记
	 * */
	@RequestMapping(value="/customer/addtempsign")
	@ResponseBody
	public String addTempSign(String id,String servicesign,String remark,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		CustomerInfoTemp cif = customerInfoTempService.getCusInfoTempById(Long.parseLong(id));
		cif.setServicesign(Integer.parseInt(servicesign));
		cif.setRemark(remark);
		customerInfoTempService.update(cif);
		return JSON.toJSONString(0);
	}
	
	/**
	 * 2017/10/11增加<br>
	 * 根据条件获取垫款/收款/付款记录条数<br>
	 * 驳回的记录不统计<br>
	 * 付款(sign=1):type=0 paytype=1 cusid contractid<br>
	 * 收款(sign=2):type=1 paytype=1 cusid contractid<br>
	 * 已绑定合同垫款(sign=3):type=0 paytype=0 cusid contractid<br>
	 * 未绑定合同垫款(sign=4):type=0 paytype=0 cusid contractid=0<br>
	 * */
	@RequestMapping(value="/customer/getmlcbytype")
	@ResponseBody
	public String getMoneyLogCountByType(String cusid,String contractid,Integer sign,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		//创建一个cml对象
		ContractMoneylog cml = new ContractMoneylog();
		// 传入客户id
		cml.setCusid(Long.parseLong(cusid));
		//传入合同id
		cml.setContractid(Long.parseLong(contractid));
		//判断获取的是哪种记录数并添加相应的条件
		if (sign == 1){
			//付款(sign=1):type=0 paytype=1
			cml.setType(0);
			cml.setPaytype(1);
		} else if (sign == 2) {
			//收款(sign=2):type=1 paytype=1
			cml.setType(1);
			cml.setPaytype(1);
		} else {
			//已绑定合同垫款(sign=3):type=0 paytype=0 cusid contractid
			//未绑定合同垫款(sign=4):type=0 paytype=0 cusid contractid=0
			cml.setType(0);
			cml.setPaytype(0);
		}
			
		//获取结果
		int result = contractMoneylogService.getcmlcountbytype(cml);
		return JSON.toJSONString(result);
	}
	
	
	/**
	 * 2017/11/27添加
	 * 统计汇总,按年，月，日统计已通过的签单数，付款金额，收款金额，垫款金额，代办金额
	 * */
	@RequestMapping(value="/customer/statistics")
	public String intoStatisticsPage(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//默认进入页面时展示今年个月份的记录
		
		//获取今年年份
		String nowtime = new SimpleDateFormat("yyyy").format(new Date());
		request.setAttribute("starttime", nowtime);
		request.setAttribute("endtime", nowtime);
		request.setAttribute("nowtime", nowtime);
		request.setAttribute("begintime", Constants.BEGINYEAR);
		//给页面一个标记
		request.setAttribute("sign", 2);
		
		return "/customercontract/statistics";
	}
	
	
	
	
	/**
	 * 2017/11/27添加
	 * ajax获取数据
	 * 这里面根据type不同，分为以下几种情况：
	 * type=1
	 * 	展示月记录
	 * 	starttime 记录的是年份 endtime记录的是null
	 * 	循环展示12个月的记录
	 * type=2
	 * 	展示日记录
	 * 	starttime 记录的是年份 endtime记录的是月份
	 * 	根据年份判断是平年还是润年，根据月份判断天数
	 * type=3
	 * 	根据starttime和endtime确定展示的是年记录还是月记录
	 * 	如果starttime和endtime相同，那就展示月记录
	 * 	如果starttime和endtime不相同，那就展示年记录
	 * type=4
	 * 	肯定是显示年份
	 * 2017/12/6日更新
	 * 	收款用业绩统计的那个sql
	 * */
	@RequestMapping(value="/customer/statisticsdata",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String statisticsData(String starttime,String endtime,String type,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//即将传入页面的数据
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		//x轴坐标显示
		List<String> xlist = new ArrayList<String>();
		//签单数
		List<String> qdlist = new ArrayList<String>();
		//收款
		List<String> sklist = new ArrayList<String>();
		//付款
		List<String> fklist = new ArrayList<String>();
		//垫款
		List<String> dklist = new ArrayList<String>();
		//代办
		List<String> dblist = new ArrayList<String>();
		//报销
		List<String> bxlist = new ArrayList<String>();
		//图例
		List<String> tllist = new ArrayList<String>();
		//标题
		List<String> titlelist = new ArrayList<String>();
		
		ContractMoneylog cml = new ContractMoneylog();
		Commission comm = new Commission();
		Paid  paid = new Paid();
		//为了收款
		Contract c = new Contract();
		c.setState(99);//标识 为已完成回款的
		
		
		//根据条件判断怎么展示数据
		if (Integer.parseInt(type) == 4 || (Integer.parseInt(type) == 3 && !starttime.equals(endtime))) {
			titlelist.add(starttime+"-"+endtime+"年度统计表");
			tllist.add("签单（单/年）");
			tllist.add("付款（万元/年）");
			tllist.add("业绩（万元/年）");
			tllist.add("垫款（万元/年）");
			tllist.add("代办（万元/年）");
			tllist.add("报销（万元/年）");
			//显示分年
			for (int i = Integer.parseInt(starttime); i <= Integer.parseInt(endtime); i++) {
				xlist.add(i+"年");
				String createdate = String.valueOf(i);
				cml.setCreatedate(createdate);
				comm.setCreatedate(createdate);
				paid.setCreatedate(createdate);
				//签单数
				cml.setCountsign(Constants.StatisticsSign.FIVE);
				qdlist.add(contractMoneylogService.getcmlcountbycreatedate(cml).toString());
				//付款
				cml.setCountsign(Constants.StatisticsSign.SEV);
				fklist.add(String.valueOf((double)contractMoneylogService.getcmlcountbycreatedate(cml)/10000));
				//垫款
				cml.setCountsign(Constants.StatisticsSign.EIG);
				dklist.add(String.valueOf((double)contractMoneylogService.getcmlcountbycreatedate(cml)/10000));
				//代办
				comm.setCountsign(2);
				dblist.add(String.valueOf((double)commissionService.getCommMoneyByCreatedate(comm)/10000));
				
				//业绩
				/*
				 * x年就是从x年01月01日-x年12月31日
				 * */
				String sttime = i+"-01-01";
				String entime = i+"-12-31";
				c.setSttime(sttime);
				c.setEntime(entime);
				sklist.add(String.valueOf((double)contractService.getAllApprovemoney(c)/10000));
			}
		} 
		if (Integer.parseInt(type) == 1 || (Integer.parseInt(type) == 3 && starttime.equals(endtime))) {
			titlelist.add(starttime+"年月度统计表");
			tllist.add("签单（单/月）");
			tllist.add("付款（万元/月）");
			tllist.add("业绩（万元/月）");
			tllist.add("垫款（万元/月）");
			tllist.add("代办（万元/月）");
			tllist.add("报销（万元/月）");
			//显示分月
			for (int i = 1;i <= 12;i++) {
				xlist.add(i+"月");
				String createdate;
				if (i < 10) {
					createdate = starttime + "-0" + i; 
				} else {
					createdate = starttime + "-" + i;
				}
				cml.setCreatedate(createdate);
				comm.setCreatedate(createdate);
				paid.setCreatedate(createdate);
				//签单数
				cml.setCountsign(Constants.StatisticsSign.ONE);
				qdlist.add(contractMoneylogService.getcmlcountbycreatedate(cml).toString());
				//付款
				cml.setCountsign(Constants.StatisticsSign.THREE);
				fklist.add(String.valueOf((double)contractMoneylogService.getcmlcountbycreatedate(cml)/10000));
				//垫款
				cml.setCountsign(Constants.StatisticsSign.FOUR);
				dklist.add(String.valueOf((double)contractMoneylogService.getcmlcountbycreatedate(cml)/10000));
				//代办
				comm.setCountsign(1);
				dblist.add(String.valueOf((double)commissionService.getCommMoneyByCreatedate(comm)/10000));

				//报销
				paid.setCountsign(1);
				bxlist.add(String.valueOf((double)paidService.getPaidTotalMoney(paid)/10000));
				
				
				//业绩
				/*
				 * x月就是从某年x月01日-某年x月31日
				 * */
				String sttime = createdate+"-01";
				String entime = createdate+"-31";
				c.setSttime(sttime);
				c.setEntime(entime);
				sklist.add(String.valueOf((double)contractService.getAllApprovemoney(c)/10000));
			}
		} 
		if (Integer.parseInt(type) == 2) {
			titlelist.add(starttime+"年"+endtime+"月日统计表");
			tllist.add("签单（单/日）");
			tllist.add("付款（元/日）");
			tllist.add("业绩（元/日）");
			tllist.add("垫款（元/日）");
			tllist.add("代办（元/日）");
			tllist.add("报销（元/日）");
			//显示分日
			int day = 31;
			int intend = Integer.parseInt(endtime);
			int intstart = Integer.parseInt(starttime);
			if (intend == 4 || intend == 6 || intend == 9 || intend == 11) {
				day = 30;
			} else if (intend == 2) {
				if (intstart % 4 == 0){
					day = 29;
				} else {
					day = 28;
				}
			}
			for (int i = 1;i <= day; i++){
				xlist.add(i+"号");
				String createdate;
				if (intend < 10) {
					endtime = "0"+intend;
				}
				if (i < 10) {
					createdate = starttime + "-" + endtime + "-0" + i; 
				} else {
					createdate = starttime + "-" + endtime + "-" + i;
				}
				cml.setCreatedate(createdate);
				comm.setCreatedate(createdate);
				paid.setCreatedate(createdate);
				//签单数
				cml.setCountsign(Constants.StatisticsSign.NIG);
				qdlist.add(contractMoneylogService.getcmlcountbycreatedate(cml).toString());
				//付款
				cml.setCountsign(Constants.StatisticsSign.ELE);
				fklist.add(String.valueOf(contractMoneylogService.getcmlcountbycreatedate(cml)));
				//垫款
				cml.setCountsign(Constants.StatisticsSign.TWE);
				dklist.add(String.valueOf(contractMoneylogService.getcmlcountbycreatedate(cml)));
				//代办
				comm.setCountsign(3);
				dblist.add(String.valueOf(commissionService.getCommMoneyByCreatedate(comm)));
				//报销
				paid.setCountsign(3);
				bxlist.add(String.valueOf(paidService.getPaidTotalMoney(paid)));
				//收款
				/*
				 * x日就是某年某月x日-某年某月x日
				 * */
				String sttime = i+"-01-01";
				String entime = i+"-12-31";
				c.setSttime(createdate);
				c.setEntime(createdate);
				sklist.add(String.valueOf(contractService.getAllApprovemoney(c)));
			}
		}
		
		map.put("name", xlist);
		map.put("qd", qdlist);
		map.put("sk", sklist);
		map.put("fk", fklist);
		map.put("dk", dklist);
		map.put("db", dblist);
		map.put("bx", bxlist);
		map.put("title", titlelist);
		map.put("tl", tllist);
		
		return JSON.toJSONString(map);
	}
	
	
	/**
	 *保存客户信息 
	 * */
	@RequestMapping(value="/customer/updcustomer")
	@ResponseBody
	public String updCustomer(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		customerService.updateCustomerInfo(ci);
		return JSON.toJSONString(true);
	}
}
